Skip to content

Instantly share code, notes, and snippets.

@tianhuil
Last active December 30, 2015 12:29
Show Gist options
  • Select an option

  • Save tianhuil/7829288 to your computer and use it in GitHub Desktop.

Select an option

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.
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]
@tianhuil
Copy link
Author

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