简体   繁体   中英

loop in python3 much slower than python2

My project involves heavy looping over stocks and stat calculations. It was written in python3. As the data gets bigger, I feel the script performance is quite slow. I attempted lua because of its fame on speed, and tried to do some tests as below, also compared to python2 as a benchmark.

Only a simple loop as a test code:

lua version

for i=1,100,1 do
    for j=1,100,1 do
        print(i*j)
    end
end

python version

for i in range(1,101):
    for j in range(1,101):
        print(i*j)

the results are as follows (tried a few time and pick the best for each group):

lua5.2.3: 0.461sec
python2.7.6: 0.429sec
python3.4: 0.85sec

What surprised me is that python2 is around 2x faster than python3.

Why? and even with a simple loop?

I thought python3 is the future for python, so I learned python3 from the beginning.

Do I really need to port back my code to python2, or any tweak I could with looping to enhance its performance in python3?

I've increased your loops and disable the output (it's much slower when it's displayed).
And I'm no python expert. But you can speed up your python code with the jit compiler pypy eg (but still slower than luajit.) Furthermore, this topic about python3 and python2 might be interesting for you too.

python

r=0
for i in range(1,10000):
    for j in range(1,10000):
        r=i*j

python3

$ time python3 loop.py 

real    0m16.612s
user    0m16.610s
sys 0m0.000s

python2

$ time python2 loop.py 

real    0m11.218s
user    0m11.190s
sys 0m0.007s

pypy

$ time pypy loop.py 

real    0m0.923s
user    0m0.900s
sys 0m0.020s

lua

local r=0
for i=1,10000,1 do
    for j=1,10000,1 do
        r=i*j
    end
end

lua 5.2.3

$ time lua loop.lua 

real    0m1.123s
user    0m1.120s
sys 0m0.000s

luajit

$ time luajit loop.lua 

real    0m0.074s
user    0m0.073s
sys 0m0.000s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM