Skip to content

Instantly share code, notes, and snippets.

Forked from cgoldberg/
Last active July 9, 2018 05:54
What would you like to do?
Python Timer Class - Context Manager for Timing Code Blocks
import logging
from contextlib import contextmanager
from timeit import default_timer
time_logger = logging.getLogger(__package__ + ".timer")
def timed_code(name=None):
next_unit = iter(("s", "ms", "ns", "us")).next
msg = "section %s took" % (name,) if name else "section took"
t0 = default_timer()
yield msg
if local.conf.debug_timings:
delta = default_timer() - t0
unit = next_unit()
while delta < 1:
delta *= 1000.0
unit = next_unit()
except StopIteration:
break"%s: %.2f%s", msg, delta, unit)
with timed_code("zzz"):
from time import sleep
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment