Skip to content

Instantly share code, notes, and snippets.

@kaetemi

kaetemi/test_malloc.c

Last active Aug 17, 2020
Embed
What would you like to do?
/* Test malloc and free performance over time for a specified allocation block size and total. */
#include <iostream>
#include <chrono>
#include <thread>
#include <cstring>
#if 0 // test HeapCompact (1/2)
#ifdef _WIN32
#include <Windows.h>
#endif
#endif
int main()
{
const ptrdiff_t sz = 64 * 1024;
const ptrdiff_t nb = ((ptrdiff_t)8 * 1024 * 1024 * 1024) / sz; // 8GB
void **blocks = new void *[nb];
std::chrono::time_point<std::chrono::steady_clock> t0 = std::chrono::steady_clock::now();
int64_t ms;
auto delta = [&]() -> int64_t {
std::chrono::time_point<std::chrono::steady_clock> t1 = std::chrono::steady_clock::now();
int64_t res = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count();
t0 = t1;
return res;
};
std::cout << "round,malloc,free" << std::endl;
for (ptrdiff_t r = 0; r < 16; ++r)
{
#if 1
std::cout << r << ",";
delta();
for (ptrdiff_t i = 0; i < nb; ++i)
{
blocks[i] = malloc(sz);
// std::cout << blocks[i] << std::endl;
memset(blocks[i], 42, sz);
}
ms = delta();
std::cout << ms << ",";
#if 0 // immediate deallocation
delta();
for (ptrdiff_t i = 0; i < nb; ++i)
{
void *a = malloc(sz);
// std::cout << blocks[i] << std::endl;
memset(a, 42, sz);
free(a);
}
ms = delta();
std::cout << ms << ",";
#endif
delta();
#if 0 // reverse deallocation order
for (ptrdiff_t i = nb - 1; i >= 0; --i)
#else
for (ptrdiff_t i = 0; i < nb; ++i)
#endif
{
free(blocks[i]);
}
ms = delta();
std::cout << ms;
delta();
#endif
#if 0 // test HeapCompact (2/2)
delta();
HeapCompact(GetProcessHeap(), 0);
ms = delta();
std::cout << "," << ms;
#endif
std::cout << std::endl;
#if 0 // alternate with -32B allocation
std::cout << r << "_B,";
delta();
for (ptrdiff_t i = 0; i < nb; ++i)
{
blocks[i] = malloc(sz - 32);
// std::cout << blocks[i] << std::endl;
memset(blocks[i], 42, sz - 32);
}
ms = delta();
std::cout << ms << ",";
for (ptrdiff_t i = 0; i < nb; ++i)
{
free(blocks[i]);
}
ms = delta();
std::cout << ms << std::endl;
#endif
}
delete[] blocks;
}
/* end of file */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.