Python 3.x 使用timeit的Python中For循环和while循环的性能差异

Python 3.x 使用timeit的Python中For循环和while循环的性能差异,python-3.x,for-loop,while-loop,Python 3.x,For Loop,While Loop,我在做一些检查时遇到了一个代码,它有while循环,我不喜欢while尝试它的版本,但结果它的性能相当差。下面是代码 import timeit sp_list = list(range(1,9801)) start = 0 bs = 1000 end = start + bs content =[] content1 = [] s="""\ while sp_list[start:end]: sp_batch = sp_list[start:end] for sp in sp

我在做一些检查时遇到了一个代码,它有while循环,我不喜欢while尝试它的版本,但结果它的性能相当差。下面是代码

import timeit

sp_list = list(range(1,9801))
start = 0
bs = 1000
end = start + bs
content =[]
content1 = []
s="""\
while sp_list[start:end]:
    sp_batch = sp_list[start:end]
    for sp in sp_batch:
        content.append(sp*sp)
    start += bs
    end += bs
"""
print("S")
x = timeit.timeit(stmt=s, number=100, setup='sp_list = list(range(1,9801));start = 0;bs = 1000;end = start + bs;content =[]')
print(x)

s1="""\
for i in range(1, len(sp_list), bs):
    content1.extend([x*x for x in sp_list[i:i+bs]])
"""

x1 = timeit.timeit(stmt=s1, number=100, setup='sp_list = list(range(1,9801));start = 0;bs = 1000;end = start + bs;content1 =[]')
print(x1)
下面是输出

('WHILE ', 0.0013229846954345703)
('FOR ', 0.05230712890625)

为什么for循环执行得相当慢?还是我缺少了一个基本技巧?

您确定没有混淆输出(例如您的代码有
print(“S”)
并且没有“WHILE”或“FOR”)吗

可以进行一些清理,使您的原始代码成为一个伟大的工具:

  • 我们必须能够从代码中获得与您相同的输出,但这里的情况并非如此,这增加了一点混乱
  • 一些重复的代码可以省略
我在
9801
中添加了一个倍数,使代码运行时间更长,结果更准确 我的机器是
for
循环更快。不使用
timeit()
函数,但结果会在多次迭代中折叠

import time

sp_list = list(range(1,9801*100))
start = 0
bs = 1000
end = start + bs

# experiment 1
now = time.time()

content = []
while sp_list[start:end]:
    sp_batch = sp_list[start:end]
    for sp in sp_batch:
        content.append(sp*sp)
    start += bs
    end += bs    

exp = time.time() - now

# experiment 2
now = time.time()
content = []

for i in range(1, len(sp_list), bs):
    content.extend([x*x for x in sp_list[i:i+bs]])

exp2 = time.time() - now


print(exp, exp2)
# 0.2183971405029297 0.12479853630065918
列表理解也比循环有一点优势:

now = time.time()
content = [x*x for i in range(1, len(sp_list), bs) for x in sp_list[i:i+bs]]
exp3 = time.time() - now
print(exp3)
# 0.09359884262084961

你说得对@Evgeny,timeit似乎在while循环中做得很快。我用时间测量时间,循环的所有时间都更快,列表理解最好。所以结果取决于测量类型。。。如果有人能解释的话会很有趣。