Last active
August 22, 2021 02:40
-
-
Save SegFaultAX/7916de1d008e94814257 to your computer and use it in GitHub Desktop.
Elapsed time context manager with checkpoints
This file contains hidden or 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
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