Last active
December 30, 2015 12:29
-
-
Save tianhuil/7829288 to your computer and use it in GitHub Desktop.
Python's timer module only takes statements as strings. Here's a timer class that you can use with a "with" statement to time even0 multi-line statements.
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
import datetime | |
class Timer: | |
def __init__(self, string=None): | |
self.string = string | |
def __enter__(self): | |
self.t1 = datetime.datetime.now() | |
def __exit__(self, exc_type, exc_value, traceback): | |
self.t2 = datetime.datetime.now() | |
if self.string: | |
print (self.string + " seconds elapsed %f") % (self.t2 - self.t1).total_seconds() | |
else: | |
print "Seconds elapsed %f" % (self.t2 - self.t1).total_seconds() | |
if __name__ == '__main__': | |
import csv, sys | |
with Timer("Opening file"): | |
with open("file.txt") as fh: | |
reader = csv.reader(fh) | |
data = [r for r in reader] | |
Thanks! I didn't know about the contextmanager at the time!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can be made somewhat cleaner with
contextlib.contextmanager
:Usage: https://gist.github.com/ajtulloch/8264086