简体   繁体   中英

What's the time complexity of list access in Python?

I'm trying to make a python function as fast as I can. Let's suppose I have a prime list and I'm calling primes[i] n times for the same i .

I've the intuition that from a certain value of n, it becomes faser to keep the value of primes[i] in a variable.

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.

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) . 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. 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.

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.

And also, try doing it in google colab or any other external machine for better results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM