Skip to content

Instantly share code, notes, and snippets.

@JanSellner
Last active January 13, 2023 21:57
Show Gist options
  • Save JanSellner/edbd86e09092a8f75e54ddcdaabadf1c to your computer and use it in GitHub Desktop.
Save JanSellner/edbd86e09092a8f75e54ddcdaabadf1c to your computer and use it in GitHub Desktop.
Measure Time in Python
from timeit import default_timer
class MeasureTime(object):
"""
Easily measure the time of a Python code block.
>>> import time
>>> with MeasureTime() as m:
... time.sleep(1)
Elapsed time: 0 m and 1.00 s
>>> round(m.elapsed_seconds)
1
"""
def __init__(self, name=''):
self.name = name
self.elapsed_seconds = 0
def __enter__(self):
self.start = default_timer()
return self
def __exit__(self, exc_type, exc_value, traceback):
end = default_timer()
seconds = end - self.start
if self.name:
tag = '[' + self.name + '] '
else:
tag = ''
self.elapsed_seconds = seconds
print('%sElapsed time: %d m and %.2f s' % (tag, seconds // 60, seconds % 60))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment