by jcelerier · 5y ago · 0 comments
eh, not that much.
use.cpp:
double rand_double() { return 16.; }
int rand_int() { return 16; }
void use(void*) { }
main.cpp: #include <iostream>
#include <chrono>
void run();
int main()
{
auto t0 = std::chrono::high_resolution_clock::now();
for(int i = 0; i < 10000000; i++) {
run();
}
auto t1 = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count() << std::endl;
}
alloc.cpp: #include <cstdlib>
int rand_int();
void use(void*);
void run()
{
auto res = malloc(rand_int());
use(res);
free(res);
}
exp.cpp: #include <cmath>
double rand_double();
void use(void*);
void run()
{
auto res = exp(rand_double());
use(&res);
}
I get ~100ms for the exp, ~130ms for the malloc/free at -O3 / -Ofast with both clang and gcc (and checking with perf ensures that the time is indeed spent in these functions). So it's a bit faster, but not exactly fast (or rather, the math functions are really fucking slow)Not only that, but the original doug lea's malloc has a bin specifically for 16 byte allocations: http://gee.cs.oswego.edu/dl/html/malloc.html (the smallest size), so you've specifically chosen a very fast example.
In order to properly test malloc() you have to pre-generate some pseudo random numbers for your allocation sizes, and allocate and free unpredictably. But it's more complicated than that, as in the very occasional case when malloc() has to ask the OS for more heap, that system call may not "finish" until your program first writes to that region of memory... (ie malloc() returns but hasn't finished!)
double rand_double() { return 16.; }
int rand_int() { return 16; }
here are profiling traces: