Last active
January 13, 2023 21:57
-
-
Save JanSellner/edbd86e09092a8f75e54ddcdaabadf1c to your computer and use it in GitHub Desktop.
Measure Time in Python
This file contains hidden or 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 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