Accurate timing of functions in python Accurate timing of functions in python python python

Accurate timing of functions in python


Use the timeit module from the Python standard library.

Basic usage:

from timeit import Timer# first argument is the code to be run, the second "setup" argument is only run once,# and it not included in the execution time.t = Timer("""x.index(123)""", setup="""x = range(1000)""")print t.timeit() # prints float, for example 5.8254# ..or..print t.timeit(1000) # repeat 1000 times instead of the default 1million


Instead of writing your own profiling code, I suggest you check out the built-in Python profilers (profile or cProfile, depending on your needs): http://docs.python.org/library/profile.html


You can create a "timeme" decorator like so

import time                                                def timeme(method):    def wrapper(*args, **kw):        startTime = int(round(time.time() * 1000))        result = method(*args, **kw)        endTime = int(round(time.time() * 1000))        print(endTime - startTime,'ms')        return result    return wrapper@timemedef func1(a,b,c = 'c',sleep = 1):    time.sleep(sleep)    print(a,b,c)func1('a','b','c',0)func1('a','b','c',0.5)func1('a','b','c',0.6)func1('a','b','c',1)