Skip to content

Instantly share code, notes, and snippets.

@guewen
Last active January 2, 2016 16:39
Show Gist options
  • Save guewen/8331602 to your computer and use it in GitHub Desktop.
Save guewen/8331602 to your computer and use it in GitHub Desktop.
Timing context manager, with indentation for nested timings (http://dabeaz.blogspot.ch/2010/02/context-manager-for-timing-benchmarks.html modified to indent by nested level).
import threading
import time
bench = threading.local()
class benchmark(object):
def __init__(self, name):
self.name = name
def __enter__(self):
if getattr(bench, 'level', None) is None:
bench.level = 0
else:
bench.level += 1
self.start = time.time()
def __exit__(self, ty, val, tb):
end = time.time()
bench.level -= 1
print("%s%s : %0.3f seconds" % (" " * bench.level, self.name, end - self.start))
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment