Timing with Module timeit (Python)

vegaseat 1 Tallied Votes 241 Views Share

Python has a module specifically made for timing built-in or owner coded functions. This code snippet explains how to use this feature.

# there are several different ways in Python to convert a number to a string
# test and time a few functions using the module timeit
# (timeit turns off garbage collection by default)
# tested with Python24    vegaseat    23aug2005

import timeit

number = 7.7

# %s uses str() decimals stay the same
def num2str1(num):
    return "%s" % num

# %f defaults to six decimals
def num2str2(num):
    return "%f" % num

print "num2str1(number) =", num2str1(number), "       type =", type(num2str1(number))
print "num2str2(number) =", num2str2(number), "  type =", type(num2str2(number))
# simply use built-in function str()
print "str(number) =", str(number), "            type =", type(str(number))

print "-"*50  # 50 dashes

# use the module timeit to time a function, need to run this about 3 times and take the average
# import function from program itself via  __main__
t = timeit.Timer('num2str1(7.7)', 'from __main__ import num2str1')
# time function 100,000 times, divide result by 100,000
# then multiply by 1,000,000 to get microseconds
# elapsed = (1000000 * t.timeit(number=100000)/100000)
# same as: elapsed = (10 * t.timeit(number=100000))
elapsed = (10 * t.timeit(number=100000))
print "Function num2str1(7.7) takes %0.3f micro-seconds/pass" % elapsed  # typical result = 4.035

t = timeit.Timer('num2str2(7.7)', 'from __main__ import num2str2')
elapsed = (10 * t.timeit(number=100000))
print "Function num2str2(7.7) takes %0.3f micro-seconds/pass" % elapsed  # typical result = 3.829

# no import needed since this is a Python built-in function
t = timeit.Timer('str(7.7)')
elapsed = (10 * t.timeit(number=100000))
print "Function str(7.7) takes %0.3f micro-seconds/pass" % elapsed   # typical result = 3.732