Home > Article > Backend Development > How many fast looping methods do you know in Python?
Hello everyone, I am somenzz, today we will study the fastest loop method in Python.
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:
def while_loop(n=100_000_000): i = 0 s = 0 while i < n: s += i i += 1 return s
def for_loop(n=100_000_000): s = 0 for i in range(n): s += i return s
def sum_range(n=100_000_000): return sum(range(n))
def sum_generator(n=100_000_000): return sum(i for i in range(n))
def sum_list_comp(n=100_000_000): return sum([i for i in range(n)])
import numpy def sum_numpy(n=100_000_000): return numpy.sum(numpy.arange(n, dtype=numpy.int64))
import numpy def sum_numpy_python_range(n=100_000_000): return numpy.sum(range(n))
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()
The execution results are as follows:
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 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.
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 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!