Created
March 12, 2022 00:11
-
-
Save tclarke/8965c344a8a7e85bc85f5b0a7e1fdc11 to your computer and use it in GitHub Desktop.
Simple performance timer context manager
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
from time import perf_counter | |
from datetime import timedelta | |
class PerfTimer: | |
def __init__(self, name="Timer"): | |
""" Create a performance timer context manager. | |
These output the start and end of a block of code and the time it took to execute. | |
They can be nested for hierarchical timing. | |
@param name The name to output in the status messages | |
>>> with PerfTime("MyProcess"): | |
... import time | |
... time.sleep(4.2) | |
MyProcess: Started | |
MyProcess: 0:00:0.4.213543 | |
""" | |
self.name = name | |
def __enter__(self): | |
self.start = perf_counter() | |
print(f'{self.name}: Started') | |
def __exit__(self, *args): | |
self.end = perf_counter() | |
self.interval = self.end - self.start | |
print(f'{self.name}: {timedelta(seconds=self.interval)}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment