piRSquared piRSquared - 1 year ago 61
Python Question

How do I access the timeit magic function directly

I want to run timing on a larger scale and output dataframes of results from the iPython

magic function. I don't want to rewrite it. How should I access directly?

I'd like something like this:

f = lambda x: (x * 4. + 2) ** .5

for i in xrange(3):
print timeit(f(i))

And I'd get some output:

100 loops: 1 s
10 loops: 10 s
10 loops: 3e9 ns

Or similar.

Answer Source

You could import the timeit module and manually specify the number of iterations:

from timeit import timeit

f = lambda x: (x * 4. + 2) ** .5

for i in xrange(3):
    num = 100
    print  '%s: %s'%(num, timeit('f(i)', number=num))

You can use repeat instead of putting your timer in a loop