Created
November 6, 2012 02:30
-
-
Save nmcv/4022183 to your computer and use it in GitHub Desktop.
Measure code execution time with Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
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