简体   繁体   中英

Elapsed time of malloc after populating unordered_map (c++)

in the following code, I implemented and populated an unordered_map (function unuseful() ), then I used malloc to allocate memory. The time elapsed for the malloc call is very high (more or less 135 milliseconds to store 1001 bytes): why?

I'm compiling using gcc4.8.1, which runs on Lubuntu 13.10. The compile command is g++ -std=c++11 main.cpp (if I add optimization like -O1 , -O2 , -O3 , -Ofast or -Wno-write-strings , the result does not change). I'm testing the efficiency of a (much more complex) program, and I really need to understand which parts take how much time.

If I remove the function unuseful() or move the code from the function unuseful() to the main function, the time becomes 0. If I allocate 1000 bytes and not 1001, the time becomes 0. If I repeat twice the experiment using a for loop, the time of the first experiment is again 135 milliseconds, the time of the second is 0.

The code follows.

#include <iostream>
#include <unordered_map>
#include <sys/time.h>
#include <unistd.h>

using namespace std;

void unuseful() {
    unordered_map <string, int> nodes;
    for (int nn = 0; nn < 1000000; nn++) {
        nodes[to_string(nn)] = nn;
    }
}

long getTimeMilliseconds() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_usec / 1000 + tv.tv_sec * 1000;
}

int main() {
    unuseful();

    long start = getTimeMilliseconds();
    int *dist = (int*) malloc(1001);
    cout << "Time: " << getTimeMilliseconds() - start << "\n";
    cout << "Something unuseful to avoid compiler optimizations: " << dist[1000] << "\n";
}

My best guess is that the heap gets over complicated, and at the exit of the unuseful() method when nodes is released the heap is fragmented, them the first malloc provokes a heap syncrhonization. For a reason I don't understand if the malloc it 1000 the heap is not cleaned up... Does it behave the same way if you retain the nodes map ?

Another idea: What if you remove the unuseful() call ? Doesn't the compiler initializes 'start and calls getTimeMilliseconds before unuseful() ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM