Last active
December 20, 2015 09:39
-
-
Save pavanky/6109309 to your computer and use it in GitHub Desktop.
malloc vs calloc in Linux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ ./test | |
size malloc + for malloc+memset calloc | |
2045 0.003761 0.002064 0.002071 | |
2046 0.003695 0.002043 0.002039 | |
2047 0.003695 0.002036 0.002044 | |
2048 0.003704 0.002038 0.002036 | |
2049 0.003734 0.002039 0.002069 | |
2050 0.004025 0.004864 0.000002 | |
2051 0.003986 0.004832 0.000002 | |
2052 0.004025 0.004823 0.000002 | |
2053 0.004050 0.004851 0.000002 | |
2054 0.004030 0.004852 0.000001 | |
2055 0.004003 0.004889 0.000002 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <malloc.h> | |
#include <string.h> | |
#include <sys/time.h> | |
struct timeval tod; | |
void start() | |
{ | |
gettimeofday(&tod, NULL); | |
} | |
double stop() | |
{ | |
struct timeval now; | |
gettimeofday(&now, NULL); | |
double secs = now.tv_sec - tod.tv_sec ; | |
double usecs = now.tv_usec - tod.tv_usec; | |
return secs + (double)usecs/1e6; | |
} | |
int main(int argc, char **argv) | |
{ | |
printf("size\t malloc + for\t malloc+memset\t calloc\n"); | |
for (int i = 2045; i <= 2055; i++) { | |
double mftime = 0, mmtime = 0, catime = 0; | |
for (int iter = 0; iter < 100; iter++) { | |
start(); | |
double *foo = (double *)malloc(i * i * sizeof(double)); | |
for (int k = 0; k < i * i; k++) foo[k] = 0; | |
mftime += stop(); | |
free(foo); | |
} | |
for (int iter = 0; iter < 100; iter++) { | |
start(); | |
double *bar = (double *)malloc(i * i * sizeof(double)); | |
memset(bar, 0, i * i * sizeof(double)); | |
mmtime += stop(); | |
free(bar); | |
} | |
for (int iter = 0; iter < 100; iter++) { | |
start(); | |
double *baz = (double *)calloc(i * i, sizeof(double)); | |
catime += stop(); | |
free(baz); | |
} | |
printf("%d\t %lf\t %lf\t %lf\n", i, mftime/100, mmtime/100, catime/100); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment