Today we'll be talking about a [decorator]
Note: The link "Decorator" refers to the decorator tutorial in the Python3 tutorial. You can get a quick overview of what a decorator is here.
@functools.lru_cache - Make function execution result memos to significantly improve recursive function execution time.
Example: Finding treasure. Find the element 'Gold Coin' in a nested tuple or list.
import time from functools import lru_cache def find_treasure(box): for item in box: if isinstance(item, (tuple, list)): find_treasure(item) elif item == 'Gold Coin': print('Find the treasure!') return True start = time.perf_counter() find_treasure(('sth', 'sth', 'sth', ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'), ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'), 'Gold Coin', )) end = time.perf_counter() run_time_without_cache = end - start print('in the absence ofCachepresent situation,The run took{} s。'.format(run_time_without_cache)) @lru_cache() def find_treasure_quickly(box): for item in box: if isinstance(item, (tuple, list)): find_treasure(item) elif item == 'Gold Coin': print('Find the treasure!') return True start = time.perf_counter() find_treasure_quickly(('sth', 'sth', 'sth', ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'), ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'), 'Gold Coin', )) end = time.perf_counter() run_time_with_cache = end - start print('possessCachepresent situation,The run took{} s。'.format(run_time_with_cache)) print('there areCachethan notCachesharp (of knives or wits){} s。'.format(float(run_time_without_cache-run_time_with_cache)))
final output
Find the treasure!
The run took 0.0002182829999810565 s without Cache.
Find the treasure!
The run took 0.00011638000000857573 s with Cache.
With Cache is 0.00010190299997248076 s faster than without Cache.
Note: My computer configuration when running this example was as follows
CPU:AMD Ryzen 5 2600 RAM:Kingston HyperX 8Gigabytes 2666
Approximately 7 months of use.
This decorator keeps track of the input values of the function as it runs along with the results of the run. When the tuple ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth') occurs for the second time, the function with the decoratorfind_the_treasure_quickly
Instead of looking up the tuple again at recursion time, the result of the run is found in the "memo" and returned!
summarize
The above is a small introduction to let you Python to a very cool accelerated recursive function decorator, I hope to help you, if you have any questions please leave me a message, I will reply to you in a timely manner. Here also thank you very much for your support of my website!