我有以下模数指数代码,我想在函数中对几行进行基准测试。 一行是:
temp = square(temp)
但是python抱怨没有定义全局名称'square'。另外我如何用
对线进行基准测试ret = temp % n
我是否还需要将其写入函数?
import math
import timeit
def int2baseTwo(x):
"""x is a positive integer. Convert it to base two as a list of integers
in reverse order as a list."""
# repeating x >>= 1 and x & 1 will do the trick
assert x >= 0
bitInverse = []
while x != 0:
bitInverse.append(x & 1)
x >>= 1
return bitInverse
def square(a):
return a ** 2
def modExp(a, d, n):
"""returns a ** d (mod n)"""
assert d >= 0
assert n >= 0
base2D = int2baseTwo(d)
#print 'base2D = ', base2D
base2DLength = len(base2D)
#print 'base2DLength = ', base2DLength
modArray = []
result = 1
temp = 1
for i in range(0, base2DLength):
if i == 0:
temp = a
continue
print(timeit.timeit("temp = square(temp)", setup="from __main__ import modExp"))
if base2D[i] == 1:
temp = temp * a
ret = temp % n
return ret
if __name__=="__main__":
print(timeit.timeit("modExp(1000,100,59)", setup="from __main__ import modExp"))