Problem with timeit

Steve D'Aprano steve+python at pearwood.info
Fri Dec 15 08:41:15 EST 2017


On Sat, 16 Dec 2017 12:25 am, ast wrote:

> 
> "Thomas Jollans" <tjol at tjol.eu> a écrit dans le message de
> news:mailman.74.1513341235.14074.python-list at python.org...
>> On 2017-12-15 11:36, ast wrote:
> 
> 
>> 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.
> 
> There are more than 100000 multiplications to perform on a
> soaring size integer. I have some doubts "x=123456**123456 "
> only takes 10 ns on your system.

You would be right.

My computer appears to be about a thousand times slower than Thomas' computer.
On my computer, it takes about a second to calculate 123456**123456, so I
predict his will take about a millisecond.


> On my computer it takes roughtly 4 s, mesured with a watch.

That's not a very accurate way to measure it. You are measuring your own
reaction time, the time it takes the interactive interpreter to parse the
text of the code, compile it, execute the code, then print a new prompt, and
then your reaction time again. The actual execution time is drowned in the
rest of the noise.

> I can't do "len(str(x))" to know the size, I have to kill the process

On my computer, that took about five minutes or so. I wasn't really paying
attention on precisely how long it took, but it was around that.


> But x.bit_length() answers 2088091, so x should have about
> 600000 digits

py> x = 123456**123456
py> s = str(x)
py> len(s)
628578



> If I measure execution time:
> 
>>>> t=time(); x=123456**123456; print(time()-t)
> 0.0
> 
> There is still something wrong

The interpreter first computes the big int 123456**123456 while it is
compiling the entire command line, so that happens *before* the time starts.
The assignment is so fast that the three statements:

t = time()
x = 5...6  # huge number, pre-calculated
print(time() - t)

essentially occurs faster than the resolution of time.time() on your machine.

Try using time.perf_counter instead.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list