Last active
December 15, 2015 16:22
-
-
Save mherrmann/898c30b7186b7167ca18 to your computer and use it in GitHub Desktop.
Measure the time taken by some Python code
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 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