在python3中循环比python2慢得多 [英] loop in python3 much slower than python2

查看:56
本文介绍了在python3中循环比python2慢得多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目涉及大量循环库存和统计数据.它是用python3编写的.随着数据变大,我觉得脚本性能很慢.我尝试使用lua是因为它在速度上享有盛誉,并尝试进行以下测试,并与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版本

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

python版本

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.461秒
python2.7.6:0.429sec
python3.4:0.85秒

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

让我惊讶的是python2比python3快2倍.

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

为什么?甚至有一个简单的循环?

Why? and even with a simple loop?

我认为python3是python的未来,所以我从一开始就学习python3.

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

我是否真的需要将我的代码移植回python2,或者我可以通过循环进行任何调整来提高其在python3中的性能?

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

推荐答案

我增加了循环并禁用了输出(显示时速度要慢得多).
而且我不是 Python 专家.但是您可以使用jit编译器pypy来加快python代码的速度,例如(但仍然比luajit慢.)此外,有关python3和python2的主题 可能对你也很有趣.

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 e.g. (but still slower than luajit.) Furthermore, this topic about python3 and python2 might be interesting for you too.

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

这篇关于在python3中循环比python2慢得多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆