Last active
August 29, 2015 14:10
-
-
Save rodrev/fe5537e44119c6576d5f to your computer and use it in GitHub Desktop.
time your python program (or parts of it) easily
This file contains 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
""" | |
Adapted from code by Huy Nguyen: http://www.huyng.com/posts/python-performance-analysis/ | |
Roddie Reventar, 2014 | |
Displays elapsed time. | |
Fast times look like: | |
>>> 1.968050e-02 seconds | |
Slow times (large data) look like: | |
>>> 0h 10m 32s | |
Use in python as follows: | |
>>> import timer | |
>>> with timer.Timer(): | |
>>> runprogram() # time your program, function or whatever is inside the 'with' block. | |
""" | |
from time import time | |
class Timer(object): | |
def __enter__(self): | |
self.t = time() | |
def __exit__(self, *args): | |
t1 = time() | |
s = t1 - self.t | |
m = int(s / 60) | |
h = int(s / 3600) | |
if s < 60: | |
print("%e seconds" % s) | |
else: | |
print("%dh %dm %ds" % (h % 60, (m - h) % 60, (s - m) % 60)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment