Welcome, guest | Sign In | My Account | Store | Cart

This recipe allows one to use the "with" statement to time sections of code.

Python, 24 lines
 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 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.

1 comment

Nick Efford 17 years, 7 months ago  # | flag

An improvement. You could instead replace the final line of the function with

L.append(end - start)

You would then use the function as follows:

t = []
with accum_time(t):
  sum(range(1000000))
with accum_time(t):
  sum(range(2000000))

This accumulates a list of times for each separate task, which you can then pass to the sum function for a final total:

total = sum(t)