作業系統 :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 獲取,
微信公眾號:
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/547344.html
標籤:Python
