Skip to content

Instantly share code, notes, and snippets.

@romech
Last active November 11, 2023 16:25
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 romech/56e7f4bb18cf93eda9ad04d87e8c34b0 to your computer and use it in GitHub Desktop.
Save romech/56e7f4bb18cf93eda9ad04d87e8c34b0 to your computer and use it in GitHub Desktop.
Measure code execution time within a block using a Python context manager
from time import perf_counter
class catchtime:
def __enter__(self):
self._time_start = perf_counter()
return self
def __exit__(self, type, value, traceback):
self.elapsed = perf_counter() - self._time_start
@romech
Copy link
Author

romech commented Nov 11, 2023

Usage example:

with catchtime() as t:
    time.sleep(0.42)

print(t.elapsed)
# 0.4206...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment