Skip to content

Instantly share code, notes, and snippets.

@tkhoa2711
Created December 17, 2014 17:15
Show Gist options
  • Save tkhoa2711/601434be5d7a77e4d201 to your computer and use it in GitHub Desktop.
Save tkhoa2711/601434be5d7a77e4d201 to your computer and use it in GitHub Desktop.
An utility module for timing code execution in Python
"""
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