cosmotool/python/cosmotool/timing.py

54 lines
1.3 KiB
Python
Raw Normal View History

import time
2014-07-28 09:33:08 +02:00
from contextlib import contextmanager
@contextmanager
def time_block(name):
2014-12-07 21:50:12 +01:00
"""
This generator measure the time taken by a step, and prints the result
in second to the console.
Arguments:
name (str): prefix to print
"""
2014-07-28 09:33:08 +02:00
ts = time.time()
yield
te = time.time()
2015-01-30 17:50:18 +01:00
print('%s %2.2f sec' % (name, te-ts))
def timeit(method):
2014-12-07 21:50:12 +01:00
"""This decorator add a timing request for each call to the decorated function.
Arguments:
method (function): the method to decorate
"""
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
2015-01-30 17:50:18 +01:00
print('%r (%r, %r) %2.2f sec' % (method.__name__, args, kw, te-ts))
return result
return timed
def timeit_quiet(method):
2014-12-07 21:50:12 +01:00
"""This decorator add a timing request for each call to the decorated function.
Same as cosmotool.timeit_ but is quieter by not printing the values of the arguments.
Arguments:
method (function): the method to decorate
"""
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
2015-01-30 17:50:18 +01:00
print('%r %2.2f sec' % (method.__name__, te-ts))
return result
return timed