piRSquared piRSquared - 4 months ago 17
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

%timeit
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

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

Comments