dependence of allocation time on the size of the requested memory of the malloc function

Viewed 61

I wrote a program to calculate the time it takes to allocate memory for a malloc function.

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main() {
    FILE *f;
    f = fopen("malloc.txt","w");
    int size = 1024*1024;
    for (int i = 1; i <= 1024; i++) {
        int *a;
        clock_t begin = clock();
        a = (int*)malloc(i*size);
        clock_t end = clock();
        free(a);
        double time = (end - begin) / CLOCKS_PER_SEC;
        fprintf(f,"%d %f\n",i, time);
    }
    fclose(f);
}

I then plot the allocation time dependency against the size of the memory to be allocatedenter image description here

can you explain to me why the graph is not increasing linearly but barely increasing and there are sudden spikes?

1 Answers

why the graph is not increasing linearly but barely increasing and there are sudden spikes?

Internally, malloc() is likely asking the OS for a larger amount of memory, and then dividing it up for subsequent allocations. The spikes are likely when malloc() has to go back to the OS to get more memory. Accordingly, free() wouldn't return memory back to the OS, it would just return it back to whatever internal pool malloc() is using to cache memory.

Related