比较Python 2 和 Python 3 在对list进行循环的执行效率

本文对Python 2 和 Python 3 对集合-list进行循环时的执行效率进行比较
  • 首先我定义了一个for_test函数,然后利用ipython的魔法函数 %timeit进行执行速度的测试
  • %timeit会自动多次执行目标函数来获得一个更准确的结果。
  • 在测试的过程,发现一个比较奇怪的问题,如果不进行赋值操作的话,单单逐个获取元素,并进行运算,Python 2 的效率高于 Python 3
  • 如果加上一个赋值的操作,则Python 3 的效率高于 Python 2
  • 但很奇怪的地方是如果我用 %time 来对函数进行一次测试,却发现Python 2 的效率却是高于 Python 3 的

用 %time 测试,只运行一次测试函数
def for_test(container):
    for i, num in enumerate(container):
        num = num/5*10 + 12 - 8
        container[i] = num
container = list(range(1000000))
%time for_test(container)
  • Python 2
Wall time: 126 ms  # 多次运行的结果都是120-130 ms左右
Wall time: 129 ms
Wall time: 128 ms
  • Python 3
Wall time: 191 ms # 多次运行均大于160ms,可以看出其效率低于Python 2 
Wall time: 176 ms
Wall time: 183 ms
用 %timeit 测试,多次运行测试函数
def for_test(container):
    for i, num in enumerate(container):
        num = num/5*10 + 12 - 8
        container[i] = num
container = list(range(1000000))
%timeit for_test(container)
  • Python 2
10 loops, best of 3: 348 ms per loop # 可以发现相对于%time的测试结果显著
  • Python 3
176 ms ± 5.96 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

如果测试函数只进行运算而不进行重新赋值,则结果会发生变化

%time

def for_test(container):
    for i, num in enumerate(container):
        num = num/5*10 + 12 - 8

container = list(range(1000000))
%time for_test(container)
  • Python 2
Wall time: 98 ms
Wall time: 96 ms
Wall time: 97 ms

Pyhton 3

Wall time: 142 ms
Wall time: 138 ms
Wall time: 175 ms

%timeit

def for_test(container):
    for i, num in enumerate(container):
        num = num/5*10 + 12 - 8

container = list(range(1000000))
%timeit for_test(container)
  • Pyhton 2
10 loops, best of 3: 96.7 ms per loop
  • Python 3
145 ms ± 4.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

总结

我的猜测是 %timeit 在Python 2 和 3 中的运行机制可能不同导致得到的结果不一样

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值