Time sections of code by using "with" statement « Python recipes « ActiveState Code (original) (raw)
This recipe allows one to use the "with" statement to time sections of code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | # Public domain from __future__ import with_statement import contextlib, time @contextlib.contextmanager def accum_time(L): """ Add time used inside a with block to the value of L[0]. """ start = time.clock() try: yield finally: end = time.clock() L[0] += end - start # Example: measure time to execute code inside with blocks. t = [0] with accum_time(t): print sum(range(1000000)) with accum_time(t): print sum(range(2000000)) print 'Time:', t[0] |
---|
If one wishes to time specific regions of code, typically the following idiom is used:
accumulated\_time = 0 start = time.clock() #### Code to be timed end = time.clock() accumulated\_time += end - startThis gets tedious if many such blocks of code must be timed throughout a program. An alternative is to use the with statement, introduced in Python 2.5\. This shortens the "code overhead" needed to time each section of code from three lines to one line.