使用LRU加速python應用

操作系統 :CentOS 7.6.1810_x64

Python 版本 : 3.9.12

一、背景描述

使用python開發過程中,會遇到需要使用緩存加速應用的情況,比如下面這些場景:

  • 數據轉換加速

字符串時間轉換成int時間戳;

字符串時間轉換成datetime類型;

...

  • 數據解析加速

bytes數據轉換爲int(數據包解析場景的端口、序列號等);

bytes數據轉換爲string(數據包解析場景的ip地址等);

...

本文提供兩種實現方式來加速應用,這裏記錄下,希望對你有幫助。 

二、具體實現

1、使用python自帶的OrderedDict實現LRU

實現思路:

1)使用OrderedDict作爲緩存,並設置大小;

2)第一次解析時,將解析結果加入緩存;

3)緩存元素數量超過設定數量,執行pop操作; 

示例代碼如下 :

from collections import OrderedDict
class LRU:

    def __init__(self, func, maxsize=128):
        self.func = func
        self.maxsize = maxsize
        self.cache = OrderedDict()

    def __call__(self, *args):
        if args in self.cache:
            value = self.cache[args]
            self.cache.move_to_end(args)
            return value
        value = self.func(*args)
        if len(self.cache) >= self.maxsize:
            self.cache.popitem(False)
        self.cache[args] = value
        return value

2、使用lru-dict庫實現LRU

pypi地址:https://pypi.org/project/lru-dict/

github地址:https://github.com/amitdev/lru-dict

 

安裝lru-dict庫:

pip install lru-dict

示例代碼:

from lru import LRU
l = LRU(5)         # Create an LRU container that can hold 5 items

print l.peek_first_item(), l.peek_last_item()  #return the MRU key and LRU key
# Would print None None

for i in range(5):
   l[i] = str(i)
print l.items()    # Prints items in MRU order
# Would print [(4, '4'), (3, '3'), (2, '2'), (1, '1'), (0, '0')]

print l.peek_first_item(), l.peek_last_item()  #return the MRU key and LRU key
# Would print (4, '4') (0, '0')

l[5] = '5'         # Inserting one more item should evict the old item
print l.items()
# Would print [(5, '5'), (4, '4'), (3, '3'), (2, '2'), (1, '1')]

由於lru-dict庫是使用c實現的,使用源代碼安裝可能存在環境問題,可直接使用pypi上面提供的預編譯whl文件:

 說明:

1)源碼包爲 lru-dict-1.1.8.tar.gz;

2)本文使用的whl文件是 lru_dict-1.1.8-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl ;

3)可從以下途徑獲取上述文件:

關注微信公衆號(聊聊博文,文末可掃碼)後回覆 2023031901 獲取。

三、運行效果

這裏演示下兩種實現方式的具體效果,並做下對比。

1、測試用例1(lru庫實現)

 測試代碼:

 運行效果:

 運行時間:15.046 秒

2、測試用例2( OrderedDict實現)

測試代碼:

 運行效果:

 運行時間: 28.934秒

 結論:

lru-dict庫比較快。

說明:

1)使用OrderedDict實現LRU的優點在於不用安裝額外的庫;

2)lru-dict是使用c語言開發的第三方庫,需要使用pip進行安裝,性能比較好,但和平臺相關性比較強; 

四、資源下載

本文涉及示例代碼及whl文件,可從百度網盤獲取:

https://pan.baidu.com/s/1N6wWHhMkvXcyVI5mEhn1JA 

關注微信公衆號(聊聊博文,文末可掃碼)後回覆 2023031901 獲取。

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