我正在尝试优化简单的字符计数功能。经过几次更改后,我决定检查计时,并期望使用基本“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/