Python 基准测试 : Why for in loop is faster than simple while?

标签 python performance benchmarking

我正在尝试优化简单的字符计数功能。经过几次更改后,我决定检查计时,并期望使用基本“while”循环的函数比“for in”循环更快。

但令我惊讶的是 while 循环比这里的 for 慢了近 30%!具有较低抽象性(内部执行较少)的简单“while”循环不应该比“for in”快得多吗?

import timeit

def faster_count_alphabet(filename):
    l = [0] * 128 # all ascii values 0 to 127
    with open(filename) as fh:
        a = fh.read()
        for chars in a:
            l[ord(chars)] += 1
    return l

def faster_count_alphabet2(filename):
    l = [0] * 128 # all ascii values 0 to 127
    with open(filename) as fh:
        a = fh.read()
        i = 0
        size = len(a)
        while(i<size):
            l[ord(a[i])] += 1
            i+=1
    return l

if __name__ == "__main__":
    print timeit.timeit("faster_count_alphabet('connect.log')", setup="from __main__ import faster_count_alphabet", number = 10)
    print timeit.timeit("faster_count_alphabet2('connect.log')", setup="from __main__ import faster_count_alphabet2", number = 10)

这是我得到的时间:

7.087787236
9.9472761879

最佳答案

While循环

在你的 while 循环中,解释器必须检查每次迭代你的表达式是否为真,因此它必须访问元素 i 和 size 并比较它们。

For 循环

另一方面,for 循环不需要这样做,因为正如 Chris_Rands 已经指出的那样,for 循环已经过优化

关于Python 基准测试 : Why for in loop is faster than simple while?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53812334/

相关文章:

c# - 为什么代码大小对于 JIT 编译很重要?

database - 确定何时扩展我的 AWS RDS 数据库?

delphi - 德尔福基准工具

pointers - 清除截断指针的更快或更慢的方法?

python - 这是否作为(std)模块 : cyclic iteration (a little like itertools. 周期存在)而没有中间内存分配

python - Django中不同应用程序的不同数据库

python - 相当于 GNU coreutils/bin/date 输出与 Python2(时区)

Java JTextPane 性能低下

Java JVM 默认垃圾收集器 : is it configured the same across different applications?

python - 如何在 python3 中的慢速测试中提前失败(例如设置超时)(最好使用nose)