[英]What's the time complexity of list access in Python?
I'm trying to make a python function as fast as I can.我正在尝试尽可能快地制作 python function。 Let's suppose I have a prime list and I'm calling
primes[i]
n times for the same i
.假设我有一个素数列表,并且我为同一个
i
调用了primes[i]
n 次。
I've the intuition that from a certain value of n, it becomes faser to keep the value of primes[i]
in a variable.我的直觉是,从 n 的某个值开始,将
primes[i]
的值保存在变量中变得更加容易。
I made some tries by comparing the two following implementations, and I can't figure out which one is the fastest.我通过比较以下两个实现进行了一些尝试,但我无法弄清楚哪个是最快的。 It looks like time access to
primes[i]
depends on a lot of factor.看起来访问
primes[i]
的时间取决于很多因素。
1st implementation第一次实施
while n != 1:
p = primes[i]
if n % p == 0:
n = n // p
factorization.append(p)
else:
i += 1
2nd implementation第二次实施
while n != 1:
if n % primes[i] == 0:
n = n // primes[i]
factorization.append(primes[i])
else:
i += 1
Is there any rule to know from how many calls it becomes interesting to keep the value of an element of a list in a variable?是否有任何规则可以从多少次调用中知道将列表元素的值保存在变量中变得有趣?
Accessing primes[i]
is done in constant time, O(1)
.访问
primes[i]
是在常数时间O(1)
内完成的。 What that means is that the time needed to read primes[i]
does not increase as the primes
becomes bigger and that it does not increase when i
becomes bigger.这意味着读取
primes[i]
所需的时间不会随着primes
变大而增加,也不会随着i
变大而增加。 In layman's terms: it's damn fast!用外行的话来说:这太他妈快了!
Then again, accessing a local variable p
is still faster than accessing primes[i]
, because the latter has to look up and call the __getitem__
implementation of the primes
object. Therefore caching a value in a local variable instead of looking up a list twice is marginally faster.再一次,访问局部变量
p
仍然比访问primes[i]
快,因为后者必须查找并调用primes
object 的__getitem__
实现。因此将值缓存在局部变量中而不是查找列表两次稍微快一点。
On the other hand, caring about marginal speed improvements is meaningless compared to reducing algorithm complexity.另一方面,与降低算法复杂度相比,关心边际速度改进是没有意义的。 For the problem of finding prime numbers, you should focus on finding a smart algorithm rather than on improving built-in-list access times.
对于寻找素数的问题,您应该专注于寻找智能算法而不是改进内置列表访问时间。
Try using a benchmark尝试使用基准
import time
start = time.time()
while n != 1:
p = primes[i]
if n % p == 0:
n = n // p
factorization.append(p)
else:
i += 1
end = time.time()
print(end - start)
do the same for implementation 2 and compare.对实现 2 做同样的事情并进行比较。
And also, try doing it in google colab or any other external machine for better results.而且,尝试在 google colab 或任何其他外部机器中进行操作以获得更好的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.