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:
<pre>accumulated_time = 0 start = time.clock()
Code to be timedend = 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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4