Problem with timeit
Peter Otten
__peter__ at web.de
Fri Dec 15 08:11:11 EST 2017
Thomas Jollans wrote:
> 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 ?
What Thomas says. Also, the value 123456**123456 is computed only once, when
the code is compiled (this is called "constant folding"). Therefore you
measure name binding only:
$ python3 -m timeit 'x = 123456**123456'
10000000 loops, best of 3: 0.0535 usec per loop
$ python3 -m timeit 'x = 123456'
10000000 loops, best of 3: 0.0535 usec per loop
Compare that with an actual calculation:
$ python3 -m timeit -s 'a = 123456' 'x = a'
10000000 loops, best of 3: 0.0539 usec per loop
$ python3 -m timeit -s 'a = 123456' 'x = a ** a'
10 loops, best of 3: 259 msec per loop
More information about the Python-list
mailing list