Skip to content

Instantly share code, notes, and snippets.

@tianhuil
Last active December 30, 2015 12:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tianhuil/7829288 to your computer and use it in GitHub Desktop.
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]
@ajtulloch
Copy link

Can be made somewhat cleaner with contextlib.contextmanager:

from contextlib import contextmanager
import datetime
import sys


@contextmanager
def timer(out=sys.stdout):
    start = datetime.datetime.now()
    yield
    end = datetime.datetime.now()
    out.write("Seconds elapsed: {}\n".format((end - start).total_seconds()))

Usage: https://gist.github.com/ajtulloch/8264086

@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