[Python-ideas] Timing hefty or long-running blocks of code

Andrew Barnert abarnert at yahoo.com
Sat Jun 1 22:28:27 CEST 2013


On Jun 1, 2013, at 2:24, Steven D'Aprano <steve at pearwood.info> wrote:

> The timeit module is great for timing small code snippets, but it is rather inconvenient for timing larger blocks of code.

If you factor the block out into a function, you can just timeit that function. And often (not always, I realize, but often) the refactoring will be worth doing anyway. After all, you have a block of code that's sufficiently separate to be worth timing separately.

> from time import time
> t = time()
> do_this()
> do_that()
> print(time() - t)

def do_them():
   do_this()
   do_that()
print(timeit(do_them, number=1))

This eliminates both of your problems. You don't have to guess which timing function to use, and it doesn't start the timer until the function starts.

In 2.x I've used your recipe, because there's no trivial way to handle this:

x = do_this()
y = do_that()

But in 3.x you just just add "nonlocal x, y" inside the function. So, I've rarely used it.

(I've also just called timeit(more_functools.sequence(do_this, do_that)), but that isn't very pythonic. If you want a new non-trivial function, it's usually better to just def it.)

Again, I realize that sometimes (even in 3.x) it's not appropriate to convey the block into a function. But often enough to be worth adding to the stdlib? I don't know.



More information about the Python-ideas mailing list