So I wanted to compare the performance of python between 2.6 and 3.1, so I wrote this simple program test.py that will perform some basic lengthy operation:
from time import time
start = time()
q = 2 ** 1000000000
q += 3 << 1000000000
print(q.__sizeof__(), time() - start)
I didn’t get what I expected, since after launching the commands time python2.6 test.py and time python3.1 test.py respectively, the output was the following:
(133333364, 0.37349200248718262)
real 0m35.586s
user 0m28.130s
sys 0m2.110s
and,
133333360 0.312520027161
real 0m26.413s
user 0m17.330s
sys 0m2.190s
I assumed that the results for both versions would be close when comparing the output of the time command and that done inside the program. What is the explanation for this?
Heh, iteresting problem, took me a while to figure it out:
Python’s compiler (!) computes q. When the script runs, the interpreter takes the time, loads the already computed value and takes the time again. Now unsurprisingly, the two times are pretty much the same.
timeon the other hand measures how long the full run (compile+run) takes.