python functools lru_cache 算法邏輯及使用示例

算法邏輯如下:

網頁鏈接爲:算法鏈接

 

相關用法:

def lru_cache(maxsize=128, typed=False):
    """Least-recently-used cache decorator.

    If *maxsize* is set to None, the LRU features are disabled and the cache
    can grow without bound. 注意:如果maxsize設置爲None,則緩存大小沒有限制,直到內存溢出,並且禁用LRU策略,改爲簡單的不同就緩存,相同就調用緩存;

    If *typed* is True, arguments of different types will be cached separately.
    For example, f(3.0) and f(3) will be treated as distinct calls with
    distinct results.注意:如果此參數設置爲True,則不同類型數據會被認爲不同的參數;如 f(3.0),f(3)都會被緩存

 

cache_info():此方法 返回 緩存相關信息

CacheInfo(hits=2, misses=6, maxsize=2, currsize=2)
hits:緩存命中個數
misses:緩存未命中個數;mises+hits 爲 調用總次數
maxsize:緩存大小
currsize:當前使用緩存大小


cache_clear() :清空緩存

 

代碼示例:

# -*- coding: utf-8 -*-
"""
(C) Guangcai Ren <[email protected]>
All rights reserved
create time '2020/3/24 14:57'

Module usage:
functools.lru_cache函數 用於緩存 函數值,緩存淘汰算法爲 最近最少使用的先淘汰
"""
import time
from functools import lru_cache


@lru_cache(maxsize=2)
def time_sleep(_time: int):
    """
    時間睡眠函數,模擬耗時操作
    :param _time:
    :return:
    """
    time.sleep(_time)
    print(f'sleep {_time}')
    return _time


sleep_list = [2, 2, 3, 3, 4, 5, 2, 1]
[time_sleep(item) for item in sleep_list]
print('調用結束後查看緩存情況', time_sleep.cache_info())
print('清空緩存', time_sleep.cache_clear())
print('再次查看清空後的緩存情況', time_sleep.cache_info())

代碼示例運行結果如下:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章