Skip to content

Instantly share code, notes, and snippets.

@shvechikov
Forked from lericson/timed_code.py
Created July 9, 2018 05:54
Show Gist options
  • Save shvechikov/89869895f642766c6b12965ed612ebc7 to your computer and use it in GitHub Desktop.
Save shvechikov/89869895f642766c6b12965ed612ebc7 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