How to speed up Python lists and dictionaries
This article focuses on "how to accelerate Python lists and dictionaries". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to accelerate Python lists and dictionaries.
Let's first write a decorator function to calculate the execution time of the function, so as to test the speed of different codes:
Import functools import time def timeit (func): @ functools.wraps (func) def newfunc (* args, * * kwargs): startTime = time.time () func (* args, * * kwargs) elapsedTime = time.time ()-startTime print ('function-{}, took {} ms to complete'.format (func.__name__, int (elapsedTime * 1000)) return newfunc
Avoid re-evaluation in the list
1. Within the cycle
Code:
Timeit def append_inside_loop (limit): nums = [] for num in limit: nums.append (num) append_inside_loop (list (range (1, 9999999)
In the above function, the function reference that .append recalculates each time through a loop. The total time spent by the above function after execution:
P-function-append_inside_loop, took 529 ms to complete
two。 Outside the cycle
Code:
Timeit def append_outside_loop (limit): nums = [] append = nums.append for num in limit: append (num) append_outside_loop (list (range (1, 9999999)
In the above function, we evaluate nums.append outside the loop and use append as a variable inside the loop. Total time:
Took p-function-append_outside_loop, took 328 ms to complete
As you can see, when we append to a local variable outside the for loop, it takes less time to speed up the code by 201 ms.
Second, avoid re-evaluation in the dictionary
1. Inside the loop
Code:
Timeit def inside_evaluation (limit): data = {} for num in limit: data [num] = data.get (num, 0) + 1 inside_evaluation (list (range (1, 9999999))
The total time spent on the above functions:
Took p-function-inside_evaluation, took 1400 ms to complete
two。 Outside the cycle
Code:
Timeit def outside_evaluation (limit): data = {} get = data.get for num in limit: data [num] = get (num, 0) + 1 outside_evaluation (list (range (1, 9999999)
The total time spent on the above functions:
Took p-function-outside_evaluation, took 1189 ms to complete
As you can see, our code speed here has been improved by 211 milliseconds.
At this point, I believe you have a deeper understanding of "how to accelerate Python lists and dictionaries". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!