Skip to content

Instantly share code, notes, and snippets.

@ruiwen
Created October 2, 2012 14:44
Show Gist options
  • Save ruiwen/3819701 to your computer and use it in GitHub Desktop.
Save ruiwen/3819701 to your computer and use it in GitHub Desktop.
Handy timer for Python functions
# From http://stackoverflow.com/a/1685337
from __future__ import with_statement
import time
class Timer(object):
def __init__(self, autoprint=False):
self.autoprint = autoprint
def __enter__(self):
self.__start = time.time()
def __exit__(self, type, value, traceback):
# Error handling here
self.__finish = time.time()
if self.autoprint:
print self.duration_in_seconds()
def duration_in_seconds(self):
return self.__finish - self.__start
# timer = Timer()
# with timer:
# # Whatever you want to measure goes here
# time.sleep(2)
# print timer.duration_in_seconds()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment