As we all know, Python is quite easy to use, but its execution performance is relatively slow compared with other languages. Fortunately, python provides a very excellent decorator to solve this problem, which is LRU_ Cache decorator. lru_ Cache is implemented through the famous LCU algorithm, which is the longest unused cache elimination algorithm recently.
In order to form a clear contrast, the recursive process of a function is implemented in a common way, that is, without adding any decorators.
def func(n): ''' Recursive sample function, without LRU added_ Cache decorator :param n: :return: ''' if n <= 1: return n return func(n - 1) + func(n - 2)
Next, use LRU_ The cache decorator is implemented once. First, the decorator module is imported.
from functools import lru_cache
The process is relatively simple, so the preparation work is completed. Then, reference it directly in the code block.
@lru_cache def func(n): ''' Recursive sample functions, adding LRU_ Cache decorator :param n: :return: ''' if n <= 1: return n return func(n - 1) + func(n - 2)
As shown in the above code, you only need to add decorators to the part of the function definition, and you’re done.
Finally, you only need to write a main function to call these two functions respectively, and obvious results will appear.
import time ''' Test consumption time ''' if __name__ == '__main__': start_time = time.time() result = func(10) end_time = time.time() cost_time = end_time - start_time print('result is ' + str(result),'cost_time is ' + str(cost_time))
Through the above @lru_ Cost can be clearly found by using examples of cache_ Time is 0.0, and the consumption of time is basically negligible. Without using this decorator, the result is obvious after half a day of calculation.
@lru_ Generally speaking, the use of cache decorator is to take the data result of each recursive calculation as the hash cache record. When this result is needed again, it will be taken directly from the cached data to avoid the performance consumption of repeated calculation. Its underlying implementation also involves the implementation and processing of bidirectional linked lists and hash tables. For a deeper level of LCU algorithm principle, you can learn some general knowledge of data structure + algorithm.
[recommended in previous periods]
Bubble sort, select the comparison between sorting and code implementation!
How to realize the monitoring behavior of keyboard and mouse through pynput and logging?
If you are a java programmer, how to call the python script you have written is actually very simple!
How to use pyqt5 to realize user login GUI interface and jump after login step by step?
Office automation: a few lines of code to convert PDF documents into word documents (code practice)!