Problem with timeit

Thomas Jollans tjol at tjol.eu
Fri Dec 15 06:47:04 EST 2017


On 2017-12-15 11:36, ast wrote:
> Hi
> 
> Time measurment with module timeit seems to work with some statements
> but not with some other statements on my computer.
> 
> Python version 3.6.3
> 
> from timeit import Timer
> 
>>>> Timer("'-'.join([str(i) for i in range(10)])").timeit(10000)
> 0.179271876732912
>>>> Timer("'-'.join([str(i) for i in range(10)])").timeit(100000)
> 1.7445643231192776
> 
> It's OK, with 10 more loops I get 10 more execution time.
> 
> But with exponentiation, it's a mess
> 
>>>> Timer("x=123456**123456").timeit(1)
> 6.076191311876755e-06
>>>> Timer("x=123456**123456").timeit(10)
> 3.841270313387213e-06
> 
> All wrong, the calculation of 123456**123456 is much longer
> than 6 microseconds, it takes few seconds, and with 10 loops timeit
> provided a shorter time ...

No, this is right. The calculation takes practically no time; on my
system, it takes some 10 ns. The uncertainty of the timeit result is at
least a few hundred nanoseconds.

Perhaps you entered 123456**123456 at a Python console (which takes a
few seconds), which makes you think the exponentiation should take that
long? In fact, it's printing the result to the console that takes time.
You can convince yourself of this by running

x=123456**123456

(which takes no time at all)

and then typing "x" (which will take seconds)



>>> Timer("x=123456**123456").timeit(10**6)
0.00969144597183913
>>> Timer("print(123456**123456, file=open('/dev/null', 'w'))").timeit(1)
4.949162941076793


-- Thomas


> 
> What happens plz ?
> 




More information about the Python-list mailing list