Skip to content

Instantly share code, notes, and snippets.

@Stefan-Code
Created January 1, 2023 21:17
Show Gist options
  • Save Stefan-Code/83d8651711a354206a7928fd82a7fa95 to your computer and use it in GitHub Desktop.
Save Stefan-Code/83d8651711a354206a7928fd82a7fa95 to your computer and use it in GitHub Desktop.
Python stopwatch context manager to measure the time of operations
import time
from contextlib import ContextDecorator
class Stopwatch(ContextDecorator):
"""
Context manager to time the duration of operations.
Example:
>>> import time
>>> with Stopwatch(timer='wall') as sw:
... time.sleep(1)
>>> print(f'Took {sw.elapsed:.0f}s')
Took 1s
"""
def __init__(self, timer='wall'):
"""
The timer type can be any of:
- wall (default): real-word clock time
- cpu: CPU performance counter (e.g. taking into account clock speed variations)
- process: Similar to cpu, but only counting our process (incl. system)
"""
if timer == 'cpu':
self.timer = time.perf_counter
elif timer == 'wall':
self.timer = time.time
elif timer == 'process':
self.timer = time.process_time
else:
raise ValueError(f'Timer type "{timer}" is invalid.')
self.elapsed = 0
def __enter__(self):
self.time = self.timer()
return self
def __exit__(self, type, value, traceback):
elapsed = self.timer() - self.time
self.elapsed = elapsed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment