Created
October 2, 2012 14:44
-
-
Save ruiwen/3819701 to your computer and use it in GitHub Desktop.
Handy timer for Python functions
This file contains hidden or 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
# 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