#include <string> #include <map> #include <vector> #include <iostream> #include "datetime.h" using namespace std; //由兩個整數合成一個64位的整數。 class CTimeId { public: uint64_t merge(int time,int uniqueid) { uint64_t newid = 0ll; const int SIZE = sizeof(int); char * p = (char *)&newid; memcpy(p,&uniqueid,SIZE); //printf("%llu\n",t); memcpy(p + SIZE,&time,SIZE); //printf("%llu\n",t); return newid; } int gettime(uint64_t &u64) { const int SIZE = sizeof(int); char * p = (char *)&u64; int time = 0; memcpy(&time,p + SIZE,SIZE); //printf("time=%d\n",time); return time; } void split(uint64_t &u64,int &time,int &uniqueid) { const int SIZE = sizeof(int); char * p = (char *)&u64; memcpy(&uniqueid,p,SIZE); //printf("uniqueid=%d\n",uniqueid); memcpy(&time,p + SIZE,SIZE); //printf("time=%d\n",time); } }; int main() { std::map<uint64_t,int> m; const int MAX = 1000000; std::vector<uint64_t> del; std::vector<uint64_t> insert; //隨機構造一堆數據 for(int i = 0;i < MAX;++i) { CTimeId timeid; int now = ::time(0); if(i % 5) { now += i * 90; } if(i % 29) { now += i * 100; } if(i % 8) { now += i * 30; } if(i % 39) { now += i * 5; } uint64_t key = timeid.merge(now,i); if(i % 50 == 0) { del.push_back(key); insert.push_back(key + i * 40); } m[key] = now; } std::map<uint64_t,int>::iterator it; int now = 0; for(it = m.begin();it != m.end();++it) { if(it->second < now) { std::cout<<"error"<<endl; } else { now = it->second; } } //統計刪除和插入的效率 CDateTime dtstart; std::cout<<del.size()<<","<<m.size()<<","<<dtstart.LongDateTime()<<endl; for(size_t i = 0,k = insert.size() - 1;i < del.size();++i,--k) { m.erase(del[i]); m.insert(make_pair(insert[i],0)); } CDateTime dtend; std::cout<<del.size()<<","<<m.size()<<","<<dtend.LongDateTime()<<","<<dtend.SubMilliSecond(dtstart)<<endl; } /* g++ -I../include aa.cpp datetime.cpp -lrt -o aa;./aa 20000,1000000,2013-01-24 15:18:34 20000,1000000,2013-01-24 15:18:34,73 g++ -I../include aa.cpp datetime.cpp -lrt -O2 -o aa;./aa 20000,1000000,2013-01-24 15:18:09 20000,1000000,2013-01-24 15:18:09,23 比較一下,對100W個元素的map,成功進行了2w次插入,2w次刪除,使用編譯器 O2優化,時間23毫秒,完全不優化,73毫秒。 */