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('在没有Cache的情况下,运行花费了{} 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('在有Cache的情况下,运行花费了{} s。'.format(run_time_with_cache))
print('有Cache比没Cache快{} s。'.format(float(run_time_without_cache-run_time_with_cache)))
|