为什么数组的直接索引比迭代快得多? [英] Why is direct indexing of an array significantly faster than iteration?

查看:73
本文介绍了为什么数组的直接索引比迭代快得多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅提供一些Python代码作为示例:

Just some Python code for an example:

nums = [1,2,3]
start = timer()
for i in range(len(nums)):
  print(nums[i])
end = timer()

print((end-start)) #computed to 0.0697546862831


start = timer()
print(nums[0])
print(nums[1])
print(nums[2])
end = timer()

print((end-start)) #computed to 0.0167170338524

我可以理解,循环中将花费一些额外的时间,因为i的值必须增加几次,但是这些值的运行时间之差两种不同的方法似乎比我预期的要大得多。

I can grasp that some extra time will be taken in the loop because the value of i must be incremented a few times, but the difference between the running times of these two different methods seems a lot bigger than I expected. Is there something else happening underneath the hood that I'm not considering?

推荐答案

简短的回答:除非,否则,是否有其他事情正在发生?循环很小。 for循环的开销很小,但是您这样做的效率很低。通过使用 range(len(nums)),您可以有效地创建另一个列表并对其进行迭代,然后无论如何都要进行相同的索引查找。尝试以下操作:

Short answer: it isn't, unless the loop is very small. The for loop has a small overhead, but the way you're doing it is inefficient. By using range(len(nums)) you're effectively creating another list and iterating through that, then doing the same index lookups anyway. Try this:

for i in nums:
    print(i)

对我来说,结果符合预期:

Results for me were as expected:

>>> import timeit
>>> timeit.timeit('nums[0];nums[1];nums[2]', setup='nums = [1,2,3]')
0.10711812973022461
>>> timeit.timeit('for i in nums:pass', setup='nums = [1,2,3]')
0.13474011421203613
>>> timeit.timeit('for i in range(len(nums)):pass', setup='nums = [1,2,3]')
0.42371487617492676

列表越大,循环的优势就越明显,因为按索引访问元素的增量成本大于循环的一次性成本: / p>

With a bigger list the advantage of the loop becomes apparent, because the incremental cost of accessing an element by index outweighs the one-off cost of the loop:

>>> timeit.timeit('for i in nums:pass', setup='nums = range(0,100)')
1.541944980621338
timeit.timeit(';'.join('nums[%s]' % i for i in range(0,100)), setup='nums = range(0,100)')
2.5244338512420654

在python 3中,它更加着重于可索引列表上的迭代器,两者的区别甚至更大:

In python 3, which puts a greater emphasis on iterators over indexable lists, the difference is even greater:

>>> timeit.timeit('for i in nums:pass', setup='nums = range(0,100)')
1.6542046590038808
>>> timeit.timeit(';'.join('nums[%s]' % i for i in range(0,100)), setup='nums = range(0,100)')
10.331634456000756

这篇关于为什么数组的直接索引比迭代快得多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆