Proper way to benchmark python code

230 Views Asked by At

I have the following modulo exponentiation code and I would like to benchmark a few lines in the function. One line is:

temp = square(temp)

But python complains that global name 'square' is not defined. Also how can I benchmark the line with

ret = temp % n

Do I also need to write it into a function?

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"))
0

There are 0 best solutions below