Let's study today Python Fastest cycle mode in .
01
All kinds of postures
For example, there is a simple task , It's from 1 Add up to 1 Billion , We can at least have 7 There are two ways to achieve , List the following :
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))
Above 7 The results of the two methods are the same , But the time consumed is different , You can guess which method is the fastest , Then look at the execution result of the following code :
import timeit
def main():
l_align = 25
print(f'{
"1、while loop ":<{
l_align}} {
timeit.timeit(while_loop, number=1):.6f}')
print(f"{
'2、for loop ':<{
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 results are shown below :
02
Faster way
for and while Essentially doing the same thing , however while Is pure Python Code , and for It's called C Extension to increment and boundary check variables , We know CPython The interpreter is C language-written ,Python Code is better than C Code is slow , and for Circulation represents C,while Circulation represents Python, therefore for Than while fast .
numpy Built in sum than Python Of sum fast
numpy Mainly used C Compiling , Same function , Must be numpy Fast , Allied ,numpy Of arange It's definitely better than Python Of range fast .
numpy Of sum And Python Of range Use a combination of , The result takes the longest , See method 7. It's best to use numpy Package to complete the task , Like the way 6.
The generator is inert , Not all at once 1 An digital , The list derivation will apply all the numbers at once , Memory occupation is high, not to mention , You can't make effective use of the cache , Therefore, the performance is slightly poor .