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. """ start = time.clock() try: yield finally: end = time.clock() L += end - start # Example: measure time to execute code inside with blocks. t =  with accum_time(t): print sum(range(1000000)) with accum_time(t): print sum(range(2000000)) print 'Time:', t
If one wishes to time specific regions of code, typically the following idiom is used:
<pre>accumulated_time = 0 start = time.clock()
Code to be timed
end = time.clock() accumulated_time += end - start</pre> This 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.
An improvement. You could instead replace the final line of the function with
You would then use the function as follows:
This accumulates a list of times for each separate task, which you can then pass to the sum function for a final total: