Popular recipes by vleon http://code.activestate.com/recipes/users/4179537/2011-10-10T04:30:11-07:00ActiveState Code RecipesBenchmark code with the with statement (Python) 2011-10-10T04:30:11-07:00vleonhttp://code.activestate.com/recipes/users/4179537/http://code.activestate.com/recipes/577900-benchmark-code-with-the-with-statement/ <p style="color: grey"> Python recipe 577900 by <a href="/recipes/users/4179537/">vleon</a> (<a href="/recipes/tags/benchmark/">benchmark</a>, <a href="/recipes/tags/speed/">speed</a>, <a href="/recipes/tags/time/">time</a>, <a href="/recipes/tags/timer/">timer</a>). </p> <p>Inspired by <a href="http://preshing.com/20110924/timing-your-code-using-pythons-with-statement">this post</a> I wrote this context manager to benchmark code blocks or function calls.</p> <p>Usage is incredibly simple:</p> <pre class="prettyprint"><code>with Timer(): ... # code to benchmark goes here </code></pre> <p>The time taken (in seconds) will be printed when the code block completes. To capture the time taken programmatically is almost as easy:</p> <pre class="prettyprint"><code>t = Timer() with t: ... # code to benchmark goes here time_taken = t.interval </code></pre> <p>Due to the difficulties of timing small snippets of code <em>accurately</em>, you should only use this for timing code blocks or function calls which take a significant amount of time to process. For micro-benchmarks, you should use the <code>timeit</code> module.</p>