Skip to content

Instantly share code, notes, and snippets.

@tclarke
Created March 12, 2022 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tclarke/8965c344a8a7e85bc85f5b0a7e1fdc11 to your computer and use it in GitHub Desktop.
Save tclarke/8965c344a8a7e85bc85f5b0a7e1fdc11 to your computer and use it in GitHub Desktop.
Simple performance timer context manager
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