Skip to content

Instantly share code, notes, and snippets.

@hyunjun
Created November 18, 2014 22:41
Show Gist options
  • Save hyunjun/53bb4bfe5f20345de5e0 to your computer and use it in GitHub Desktop.
Save hyunjun/53bb4bfe5f20345de5e0 to your computer and use it in GitHub Desktop.
timer using contextmanager
# https://docs.python.org/dev/library/contextlib.html#contextlib.ContextDecorator
# http://preshing.com/20110924/timing-your-code-using-pythons-with-statement/
$ python2.7
Python 2.7.6 (default, Nov 26 2013, 12:13:15)
[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from contextlib import contextmanager
>>> import time
>>> @contextmanager
... def timer():
... start = time.clock()
... yield
... elapsed = time.clock() - start
... print 'elapsed time {}'.format(elapsed)
...
>>> t = timer()
>>> with t:
... for i in range(1000000):
... pass
...
elapsed time 0.12
>>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment