Skip to content

Instantly share code, notes, and snippets.

@nmcv
Created November 6, 2012 02:30
Show Gist options
  • Save nmcv/4022183 to your computer and use it in GitHub Desktop.
Save nmcv/4022183 to your computer and use it in GitHub Desktop.
Measure code execution time with Python
'''
A quick way of timing code runs in Python using decorators
'''
import time
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
print '%r (%r, %r) %2.4f sec' % \
(method.__name__, args, kw, te-ts)
return result
return timed
class Foo(object):
@timeit
def foo(self, a=2, b=3):
time.sleep(0.2)
return 42
@timeit
def f1():
time.sleep(1)
print 'f1'
@timeit
def f2(a):
time.sleep(2)
print 'f2',a
@timeit
def f3(*args, **kw):
time.sleep(0.3)
print 'f3', args, kw
f1()
f2(42)
f3(42, 43, foo=2)
Foo().foo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment