亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python 如何手動(dòng)編寫(xiě)一個(gè)自己的LRU緩存裝飾器的方法實(shí)現(xiàn)

 更新時(shí)間:2021年12月26日 16:48:53   作者:蠢萌的二狗子  
本文主要介紹了Python如何手動(dòng)編寫(xiě)一個(gè)自己的LRU緩存裝飾器,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

LRU緩存算法,指的是近期最少使用算法,大體邏輯就是淘汰最長(zhǎng)時(shí)間沒(méi)有用的那個(gè)緩存,這里我們使用有序字典,來(lái)實(shí)現(xiàn)自己的LRU緩存算法,并將其包裝成一個(gè)裝飾器。

1、首先創(chuàng)建一個(gè)my_cache.py文件 編寫(xiě)自己我們自己的LRU緩存算法,代碼如下:

import time
from collections import OrderedDict
 
'''
基于LRU,近期最少用緩存算法寫(xiě)的裝飾器。
'''
 
 
class LRUCacheDict:
    def __init__(self, max_size=1024, expiration=60):
        self.max_size = max_size
        self.expiration = expiration
 
        self._cache = {}
        self._access_records = OrderedDict()  # 記錄訪問(wèn)時(shí)間
        self._expire_records = OrderedDict()  # 記錄失效時(shí)間
 
    def __setitem__(self, key, value):  # 設(shè)置緩存
        now = int(time.time())
        self.__delete__(key)  # 刪除原有使用該Key的所有緩存
 
        self._cache[key] = value
        self._access_records = now  # 設(shè)置訪問(wèn)時(shí)間
        self._expire_records = now + self.expiration  # 設(shè)置過(guò)期時(shí)間
        self.cleanup()
 
    def __getitem__(self, key):  # 更新緩存
        now = int(time.time())
        del self._access_records[key]  # 刪除原有的訪問(wèn)時(shí)按
        self._access_records[key] = now
        self.cleanup()
 
    def __contains__(self, key):  # 這個(gè)是字典默認(rèn)調(diào)用key的方法
        self.cleanup()
        return key in self._cache
 
    def __delete__(self, key):
        if key in self._cache:
            del self._cache[key]  # 刪除緩存
            del self._access_records[key]  # 刪除訪問(wèn)時(shí)間
            del self._expire_records[key]  # 刪除過(guò)期時(shí)間
 
    def cleanup(self):  # 用于去掉無(wú)效(超過(guò)大?。┖瓦^(guò)期的緩存
        if self._expire_records is None:
            return None
 
        pending_delete_keys = []
        now = int(time.time())
        for k, v in self._expire_records.items():  # 判斷緩存是否失效
            if v < now:
                pending_delete_keys.append(k)
 
        for del_k in pending_delete_keys:
            self.__delete__(del_k)
 
        while len(self._cache) > self.max_size:  # 判斷緩存是否超過(guò)長(zhǎng)度
            for k in self._access_records.keys():  # LRU 是在這里實(shí)現(xiàn)的,如果緩存用的最少,那么它存入在有序字典中的位置也就最前
                self.__delete__(k)
                break

代碼邏輯其實(shí)很簡(jiǎn)單,上面的注釋已經(jīng)很詳細(xì)了,不懂的話多看幾次。這里實(shí)現(xiàn)LRU邏輯的其實(shí)是有序字典OrderedDict,你最先存入的值就會(huì)存在字典的最前面。當(dāng)一個(gè)值使用時(shí)候,我們會(huì)重新儲(chǔ)存過(guò)期時(shí)間,導(dǎo)致被經(jīng)常使用的緩存,會(huì)存在字典的后面。而一但緩存的內(nèi)容長(zhǎng)度超過(guò)限制時(shí)候,這里會(huì)調(diào)用有序字典最前面的key(也即是近期相對(duì)用的最少的),并刪除對(duì)應(yīng)的內(nèi)容,以達(dá)到LRU的邏輯。

2、在將我們寫(xiě)好的算法改成裝飾器:

from functools import wraps
from my_cache import LRUCacheDict
 
 
def lru_cache(max_size=1024, expiration=60, types='LRU'):
    if types == 'lru' or types == 'LRU':
        my_cache = LRUCacheDict(max_size=max_size, expiration=expiration)
 
    def wrapper(func):
        @wraps(func)
        def inner(*args, **kwargs):
            key = repr(*args, **kwargs)
            try:
                result = my_cache[key]
            except KeyError:
                result = func(*args, **kwargs)
                my_cache[key] = result
            return result
 
        return inner
 
    return wrapper

這里需要解釋的是直接使用 my_cache[key],這個(gè)類(lèi)似字典的方法,實(shí)際上是調(diào)用了 LRUCacheDict 中的 __contations__方法,這也是字典中實(shí)現(xiàn)通過(guò)key取值的方法。這個(gè)裝飾器里,我加入了types的參數(shù),你們可以根據(jù)需求,實(shí)現(xiàn)不同的緩存算法,豐富這個(gè)裝飾器的功能,而lru緩存本身,其實(shí)已經(jīng)是python的標(biāo)準(zhǔn)庫(kù)了,可以引入functools.lru_cache來(lái)調(diào)用。

到此這篇關(guān)于Python 如何手動(dòng)編寫(xiě)一個(gè)自己的LRU緩存裝飾器的方法實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python LRU緩存裝飾器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論