lru c++ 實現

LRU(Least recently used,最近最少使用),數據插入隊列中,經常訪問的數據單元靠近列表頭部,不經常訪問的靠近列表尾部。列表數據就像按照時間排序一樣。常用來淘汰一些長時間不使用的數據。

更精彩內容,可以關注我的博客:wenfh2020.com



算法流程

lru 算法用一個列表也可以實現。只是列表數據需要更新操作,那得先查找數據,列表的查找時間複雜度是 O(n)O(n),這是個低效的操作,所以用時間複雜度爲 $ O(1) $ 的哈希表 std::unordered_map 輔助實現查找。

lru 算法流程


算法實現

簡單實現 LRU 算法的添加,更新和刪除最舊數據功能。定時測試相關接口操作。(測試源碼放在 github)

#ifndef _LRU_H_
#define _LRU_H_

#include <iostream>
#include <list>
#include <unordered_map>

class data {
   public:
    data() {}
    data(const data& d) : m_key(d.m_key), m_value(d.m_value) {}
    data(const std::string& key, const std::string& value)
        : m_key(key), m_value(value) {}

   public:
    std::string get_key() const { return m_key; }
    void set_key(const std::string& key) { m_key = key; }
    std::string get_value() const { return m_value; }
    void set_value(const std::string& value) { m_value = value; }

   private:
    std::string m_key;
    std::string m_value;
};

class lru {
   public:
    lru() {}
    virtual ~lru();
    bool insert(const std::string& key, const std::string& value);
    bool update(const std::string& key, const std::string& value);
    const data* get_random();
    bool pop();
    bool check();

   private:
    std::list<data*> m_list;
    std::unordered_map<std::string, std::list<data*>::iterator> m_map;
};

#endif  //_LRU_H_
...

int main() {
    lru o;
    int i = 0;
    srand((unsigned)time(NULL));

    while (i++ <= 50) {
        if (i % 3 == 1) {
            o.insert(std::to_string(i), cur_time());
        } else if (i % 8 == 0) {
            o.pop();
        } else {
            const data* d = o.get_random();
            if (d) {
                o.update(d->get_key(), cur_time());
            }
        }

        o.check();
        sleep(2);
    }
    return 0;
}

redis 近似 lru 算法

redis 數據庫 maxmemory 數據淘汰策略,通過採樣實現了近似 LRU 的算法,有興趣的朋友可以參考我的帖子 [redis 源碼走讀] maxmemory 數據淘汰策略


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