Created
December 17, 2014 17:15
-
-
Save tkhoa2711/601434be5d7a77e4d201 to your computer and use it in GitHub Desktop.
An utility module for timing code execution in Python
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
""" | |
An utility module for timing code execution in various ways. | |
""" | |
import time | |
import platform | |
from functools import wraps | |
from contextlib import contextmanager | |
""" | |
Helper function to get current time platform-independently. | |
""" | |
get_time = time.clock if platform.system() == 'Windows' else time.time | |
class Timer(object): | |
""" A timer that performs timing of an execution block.""" | |
def __init__(self, text="Timer", *args, **kwargs): | |
self.text = text | |
def __enter__(self): | |
self._start = get_time() | |
return self # allow assignment of self object within the "with" statement | |
def __exit__(self, *args): | |
self._end = get_time() | |
interval = self._end - self._start | |
print "%s: %f second" % (self.text, interval) | |
def timing(func): | |
""" A decorator for timing a function execution. """ | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
with Timer(name): | |
return func(*args, **kwargs) | |
return wrapper | |
@contextmanager | |
def timethis(label): | |
start = get_time() | |
try: | |
yield | |
finally: | |
end = get_time() | |
print '%s: %0.5f' % (label, end - start) | |
if __name__ == "__main__": | |
with Timer(): | |
print "test timer" | |
with Timer("test timer with text"): | |
time.sleep(3) | |
with timethis('test timing'): | |
n = 1000000 | |
while n > 0: | |
n -= 1 | |
@timing | |
def test_timing(): | |
print "test timing" | |
test_timing() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment