#include <map>
#include <sys/time.h>
#include <stdio.h>
#include <stdint.h>
using namespace std;
uint64_t timems()
{
timeval time;
::gettimeofday(&time, 0);
return time.tv_sec * 1000 + time.tv_usec / 1000;
}
int main()
{
map<long, long> test_mm;
long cc = 0;
uint64_t t_start = timems();
for (int i = 0; i < 4000000; i++)
{
if (test_mm.find(i) != test_mm.end()){} // find a empty map
cc++;
}
printf("time cost %ld ms\n", timems() - t_start);
return 0;
}
As shown in the above code, I perform a query operation of an empty map in a large loop. The time-consuming of this code reaches 220ms. When I commented out if (test_mm.find(i) != test_mm.end()){}
line, the time-consuming of this loop code is only 14ms. I repeated the experiment many many times, and the time-consuming comparison of of the two pieces of code is basically the same. Why is there such much performance overhead for finding an empty map in C++? The gcc version I use is 4.8.5. My compile command is g++ test.cpp -o test
.