How many fast looping methods do you know in Python?

WBOY
Release: 2023-04-13 09:13:06
forward
1815 people have browsed it

Hello everyone, I am somenzz, today we will study the fastest loop method in Python.

Various postures

For example, there is a simple task, which is to accumulate from 1 to 100 million. We can achieve it in at least 7 ways, listed as follows:

1. while loop

def while_loop(n=100_000_000):
i = 0
s = 0
while i < n:
s += i
i += 1
return s
Copy after login

2. for loop

def for_loop(n=100_000_000):
s = 0
for i in range(n):
s += i
return s
Copy after login

3. sum range

def sum_range(n=100_000_000):
return sum(range(n))
Copy after login

4. sum generator

def sum_generator(n=100_000_000):
return sum(i for i in range(n))
Copy after login

5. sum list comprehension (list comprehension)

def sum_list_comp(n=100_000_000):
return sum([i for i in range(n)])
Copy after login

6, sum numpy

import numpy
def sum_numpy(n=100_000_000):
return numpy.sum(numpy.arange(n, dtype=numpy.int64))
Copy after login

7, sum numpy python range

import numpy
def sum_numpy_python_range(n=100_000_000):
return numpy.sum(range(n))
Copy after login

The results obtained by the above 7 methods are the same. However, the time consumed varies. You can guess which method is the fastest, and then look at the execution results of the following code:

import timeit

def main():
l_align = 25
print(f'{"1、while 循环":<{l_align}} {timeit.timeit(while_loop, number=1):.6f}')
print(f"{'2、for 循环':<{l_align}}{timeit.timeit(for_loop, number=1):.6f}")
print(f'{"3、sum range":<{l_align}} {timeit.timeit(sum_range, number=1):.6f}')
print(f'{"4、sum generator":<{l_align}} {timeit.timeit(sum_generator, number=1):.6f}')
print(f'{"5、sum list comprehension":<{l_align}} {timeit.timeit(sum_list_comp, number=1):.6f}')
print(f'{"6、sum numpy":<{l_align}} {timeit.timeit(sum_numpy, number=1):.6f}')
print(f'{"7、sum numpy python range":<{l_align}} {timeit.timeit(sum_numpy_python_range, number=1):.6f}')

if __name__ == '__main__':
main()
Copy after login

The execution results are as follows:

How many fast looping methods do you know in Python?

A faster way

for than while block

for and while are essentially doing the same thing, but while is pure Python code, while for calls a C extension To increment and bound check variables, we know that the CPython interpreter is written in C language, Python code is slower than C code, and the for loop represents C, and the while loop represents Python, so for is faster than while.

numpy's built-in sum is faster than Python's sum

numpy is mainly written in C. For the same function, numpy is definitely faster. Similarly, numpy's arange is definitely faster than Python's. range fast.

Crossed use will be slower

Numpy's sum is used in combination with Python's range, and the result is the longest, see method 7. It is best to use the numpy package to complete the task, like method 6.

Generators are faster than list comprehensions

Generators are lazy and will not generate 100 million numbers at once, while list comprehensions will allocate all the numbers at once, occupying less memory. Not to mention being higher, the cache cannot be used effectively, so the performance is slightly worse.

The above is the detailed content of How many fast looping methods do you know in Python?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!