为什么Python';s";while next(迭代器,False)";比”快400倍;因为我在someList中;?
我是python的新手,担心自己做错了什么。 下面的测试似乎表明,显式地使用迭代器使用构造进行循环为什么Python';s";while next(迭代器,False)";比”快400倍;因为我在someList中;?,python,performance,loops,iterator,Python,Performance,Loops,Iterator,我是python的新手,担心自己做错了什么。 下面的测试似乎表明,显式地使用迭代器使用构造进行循环 whilenext(迭代器,False) 比明显更像蟒蛇的蛇快400倍 用于somelist中的i ,无论是在循环中还是在列表中 此测试的输出为 while(next) -> Iterations = 100,000 listLength = 1,000 seconds = 0.012 seconds iteration through the
whilenext(迭代器,False)
比明显更像蟒蛇的蛇快400倍
用于somelist中的i
,无论是在循环中还是在列表中
此测试的输出为
while(next) -> Iterations = 100,000 listLength = 1,000 seconds = 0.012 seconds
iteration through the list -> Iterations = 100,000 listLength = 1,000 seconds = 4.971 seconds
list comprehension -> Iterations = 100,000 listLength = 1,000 seconds = 3.704 seconds
这是后两种方法在内部循环中执行try-except
的结果吗?
当列表长度为1000个元素时,差异似乎太大,因此只有0.10%的时间抛出异常
是别的吗?包括我的一个严重错误
import time
ITER = 100000
for listLength in range(1000,1001,100):
inputs =[1] * listLength
#print(inputs)
#check with if test
i = iter(inputs)
newlist=[]
print(newlist)
startTime = time.perf_counter()
for j in range(0,ITER):
theInput = next(i,False) #This is on 3.6 and assignment is not an expression until 3.8, hence this line being in two places
while theInput:
newlist.append( 1/theInput)
theInput = next(i,False)
print('while(next)-> Iterations = {:,} listLength = {:,} seconds = {:6.3f} seconds'
.format(ITER,listLength,time.perf_counter() - startTime) )
#check just iterating therough the list which presumably does a try except
startTime = time.perf_counter()
for j in range(0,ITER):
for theInput in inputs:
x = 1/theInput
print('pythonic iteration through the list -> Iterations = {:,} listLength = {:,} seconds = {:6.3f} seconds'
.format(ITER,listLength,time.perf_counter() - startTime) )
#check list comprehension
startTime = time.perf_counter()
for j in range(0,ITER):
newlist =[1/theInput for theInput in inputs]
print('pythonic list comprehension -> Iterations = {:,} listLength = {:,} seconds = {:6.3f} seconds'
.format(ITER,listLength,time.perf_counter() - startTime) )
您需要将
i=iter(inputs)
放入范围(0,iter)中j的循环中。在while循环方法中,i在j的第一次迭代中耗尽。j for ITER(100000)的其余迭代实际上没有任何作用。按照Mateen的评论,每次循环开始时,for The Input in inputs
隐式调用ITER(inputs)
;在你的while
检查中,有100000个电话你没有打。而且“pythonic迭代”没有建立newlist
我运行了你的测试的固定版本,我得到了while->19秒
和pythonic->6秒
。