0
#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.

  • 6
    because you asked the compiler to produce a slow program. Try to turn on compiler optimizations `-O3` or `-O2`, The default is no optimizations because it is faster to compile, and often while developing you want fast compile and dont care about the runtime performance – 463035818_is_not_an_ai Nov 16 '22 at 07:56
  • 1
    see eg here: https://godbolt.org/z/8jKTro1xa 0ms as expected. Note that as you are not using the result of `cc` the compiler can optimize the whole loop away. – 463035818_is_not_an_ai Nov 16 '22 at 08:03
  • 1
    and even if you did print the value of `cc` after the loop the compiler would realize that no loop is needed but can be replaced by `cc = 4000000;` – 463035818_is_not_an_ai Nov 16 '22 at 08:04
  • 1
    https://stackoverflow.com/questions/15718262/what-exactly-is-the-as-if-rule – 463035818_is_not_an_ai Nov 16 '22 at 08:04
  • 1
    That's 51.5 nanoseconds per find-and-compare-and-branch, which doesn't strike me as bad at all in an unoptimized buld. – molbdnilo Nov 16 '22 at 08:05
  • 1
    indeed what you see is not "overhead". Without optimizations the program does just what you wrote down in code, no overhead is added. Its the shortcuts and clever tricks that the optimizer can do that result in something faster. – 463035818_is_not_an_ai Nov 16 '22 at 08:07

0 Answers0