亚麻:Cache Missing

本文介绍了一种使用链表实现的缓存淘汰算法,通过迭代输入序列并利用链表存储缓存元素,来统计缓存未命中次数。该算法适用于需要频繁删除和插入操作的场景。

这是亚麻OA 题

// find all the N substring with only one duplicate character.
#include <iostream>     // std::cout
#include <algorithm>    // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap
#include <vector>       // std::vector
#include <unordered_map>
#include <unordered_set>
#include <numeric>
#include <sys/time.h>
#include <list>

//main point : use list to store the cached elements.
//solution : using list to store the cached elements and then iterate the input sequence.
using namespace std;

int CacheMiss ( vector<int>& nums, int size){
    std::list<int> ls;  //why use list? frequently delete and insert.
    
    int missCnt =0;
    for (auto& e: nums){
        if (ls.size() < size){
            ls.push_back (e);
            missCnt ++;
            cout<< "missing "<< e << endl;
            continue;
        }

        auto itor = find(ls.begin(),ls.end(),e);
        if (itor != ls.end()){//e exist in list. hit.  delete the exist one in the list and push_back it into list again.
            ls.erase(itor);
            ls.push_back(e);
               cout<< "hiting "<< e << endl;
        }
        else {// missing     delete  the first one in the list and push_back new one into list.
            cout<< "pop out " <<ls.front();
            ls.pop_front();
            
            ls.push_back(e);
           cout<< " missing "<< e << endl;
            missCnt ++;
        }    
    }
    return missCnt;
}
int main () { //get the start time. struct timeval tv; gettimeofday(&tv,NULL); long ts = tv.tv_sec * 1000 + tv.tv_usec / 1000; //*** call the function . vector<int> in = {1, 2, 3, 4, 5, 4, 1}; auto out = CacheMiss(in , 4); cout<< " the missing time is: " << out << endl; //*** end of the call //get the time of end. gettimeofday(&tv,NULL); long te = tv.tv_sec * 1000 + tv.tv_usec / 1000; //output the time of the running. cout<<endl<< endl<< "running tmie is : " << te - ts << endl; return 0; }

 

转载于:https://www.cnblogs.com/HisonSanDiego/p/8283259.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值