# We want to measure (and log) how long a chunk of code # took to execute. # # We can use time.time() function to get a timestamp right # before and right after, and print out the difference. # # Implement logging the duration of the execution from __future__ import print_function import time import random import contextlib @contextlib.contextmanager def timeit(): """Context manager which logs the duration of execution. >>> with timeit(): # doctest: +ELLIPSIS ... time.sleep(1) Calculations took 1...s >>> with timeit(): # doctest: +ELLIPSIS ... time.sleep(3) Calculations took 3...s """ start = time.time() try: yield finally: print('Calculations took {:.2g}s'.format(time.time() - start)) def long_haul(*args): "Uses time.sleep() to simulate long calculations" time.sleep(5 * random.random()) return sum(args) if __name__ == '__main__': print('Will do calculations now') with timeit(): ans = long_haul(1, 2, 3) print(ans) # Please note: # We could do it also in the traditional way # using something like: # # print('Will do calculations now') # start = time.time() # ans = long_haul() # duration = time.time() - start # print('Calculations took {}s'.format(duration)) # # but this is harder to read, and leaves the # 'start' and 'duration' names in the local scope. # # To test this file, use: # py.test-3.4 --doctest-modules cm_timer.py -v # or # python3 -m doctest cm_timer.py