Skip to content

Instantly share code, notes, and snippets.

@SegFaultAX
Last active August 22, 2021 02:40
Show Gist options
  • Save SegFaultAX/7916de1d008e94814257 to your computer and use it in GitHub Desktop.
Save SegFaultAX/7916de1d008e94814257 to your computer and use it in GitHub Desktop.
Elapsed time context manager with checkpoints
from __future__ import print_function
import time
import contextlib
def format_checkpoints(cps):
pairs = [cps[i:i+2] for i in range(len(cps)-1)]
fmts = ["{0[0]} to {1[0]} in {2:.04f}s".format(start, end, end[1] - start[1])
for start, end in pairs]
return ", ".join(fmts)
@contextlib.contextmanager
def elapsed(name, logger=print):
checkpoints = []
def _checkpoint(cp):
checkpoints.append((str(cp), time.time()))
_checkpoint("start")
yield _checkpoint
_checkpoint("end")
elapsed = checkpoints[-1][1] - checkpoints[0][1]
logger(format_checkpoints(checkpoints))
logger("Total elapsed time {:.04f}s".format(elapsed))
# Example:
# with elapsed("foobar") as cp:
# time.sleep(1)
# cp("foobaz")
# time.sleep(1)
# cp("foobar")
# time.sleep(1)
#
# Output:
# start to foobaz in 1.0012s, foobaz to foobar in 1.0010s, foobar to end in 1.0012s
# Total elapsed time 3.0034s
#
# with elapsed("other thing", logging.info) as cp:
# time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment