Howto time function execution with Python

I recently had a requirement to test performance of a function call in a python script I have written. After searching the web, I finally stumbled upon a python module called timeit. After searching how to use it, I stumbled upon this blog post that explains how to wrap a function call and execute that function with timeit several times to get average execution time.
So, here's the code that I've taken from above mentioned blog post.

def wrapper(func, *args, **kwargs):
    def wrapped():
        return func(*args, **kwargs)
    return wrapped

After creating a wrapper function, we can execute our own methods like so:

from timeit import timeit
 
def method1():
  print "This method takes no parameters"
 
def method2(arg1):
  print "This method takes 1 parameter and it was: %s" % arg1
 
def method3(arg1, arg2):
  print "This method takes 2 parameters and they are: '%s' and '%s'" % (arg1, arg2)
 
m1_w = wrapper(method1)
m2_w = wrapper(method2, "arg1")
m3_w = wrapper(method3, "arg1", "arg2")
 
m1_t = timeit(m1_w, number=100)
m2_t = timeit(m2_w, number=100)
m3_t = timeit(m3_w, number=100)
 
print "Average execution time of method 1 was: %s" % m1_t
print "Average execution time of method 2 was: %s" % m2_t
print "Average execution time of method 3 was: %s" % m3_t

After executing code above, each method is going to be executed 100 (as per the number parameter to the timeit function).

Edit (05/05/14):
Following Edwards suggestion from the comments below a better approach would be something like so:

from time import time
 
startTime = time()
for x in range(0, 100):
  # make your function call
average_time = (time() - startTime) / 100

Have fun timing your function performance!

Comments