-
-
Save lericson/2945781 to your computer and use it in GitHub Desktop.
Python Timer Class - Context Manager for Timing Code Blocks
This file contains 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
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