Skip to content

Instantly share code, notes, and snippets.

@lericson
Forked from cgoldberg/timer.py
Last active July 9, 2018 05:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lericson/2945781 to your computer and use it in GitHub Desktop.
Save lericson/2945781 to your computer and use it in GitHub Desktop.
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")
@contextmanager
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()
try:
yield msg
finally:
if local.conf.debug_timings:
delta = default_timer() - t0
unit = next_unit()
while delta < 1:
delta *= 1000.0
try:
unit = next_unit()
except StopIteration:
break
time_logger.info("%s: %.2f%s", msg, delta, unit)
with timed_code("zzz"):
from time import sleep
sleep(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment