Skip to content

Instantly share code, notes, and snippets.

@mherrmann
Last active December 15, 2015 16:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mherrmann/898c30b7186b7167ca18 to your computer and use it in GitHub Desktop.
Save mherrmann/898c30b7186b7167ca18 to your computer and use it in GitHub Desktop.
Measure the time taken by some Python code
from collections import OrderedDict
from time import time
class Timer(object):
"""
Measure the time taken by some Python code, incl. its subtasks:
>>> with Timer('parent') as timer:
... sleep(0.5)
... with timer.child('child') as child:
... sleep(.25)
... with child.child('grandchild'):
... sleep(.1)
...
>>> print(timer.summary)
parent: 0.86s
child: 0.36s
grandchild: 0.10s
"""
def __init__(self, name):
self.name = name
self.elapsed = 0.0
self.start_time = None
self.children = OrderedDict()
def __enter__(self):
self.start_time = time()
return self
def child(self, name):
return self.children.setdefault(name, Timer(name))
@property
def summary(self):
result_lines = ['%s: %.2fs' % (self.name, self.elapsed)]
for child in self.children.values():
for line in child.summary.split('\n'):
result_lines.append(' ' + line)
return '\n'.join(result_lines)
def __exit__(self, *_):
time_taken = time() - self.start_time
self.elapsed += time_taken
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment