From f55574d5983e1ea8058bc3dda5d91bba649e0288 Mon Sep 17 00:00:00 2001 From: Milian Wolff Date: Fri, 26 Feb 2016 21:47:30 +0100 Subject: [PATCH] Add executable to measure malloc overhead. --- tests/benchmarks/CMakeLists.txt | 2 + tests/benchmarks/measure_malloc_overhead.cpp | 58 ++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 tests/benchmarks/measure_malloc_overhead.cpp diff --git a/tests/benchmarks/CMakeLists.txt b/tests/benchmarks/CMakeLists.txt index 39ea65a..aef438f 100644 --- a/tests/benchmarks/CMakeLists.txt +++ b/tests/benchmarks/CMakeLists.txt @@ -15,4 +15,6 @@ if (HAVE_MALLOC_H) include_directories(${SPARSEHASH_INCLUDE_DIRS}) add_executable(bench_pointersparsehash bench_pointersparsehash.cpp) endif() + + add_executable(measure_malloc_overhead measure_malloc_overhead.cpp) endif() diff --git a/tests/benchmarks/measure_malloc_overhead.cpp b/tests/benchmarks/measure_malloc_overhead.cpp new file mode 100644 index 0000000..9d811de --- /dev/null +++ b/tests/benchmarks/measure_malloc_overhead.cpp @@ -0,0 +1,58 @@ +/* + * Copyright 2016 Milian Wolff + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Library General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program; if not, write to the + * Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#include +#include +#include + +using namespace std; + +inline void escape(void* p) +{ + asm volatile("" : : "g"(p) : "memory"); +} + +int main() +{ + const auto log2_max = 17; + const auto max_steps = log2_max * 2 + 1; + unsigned int cost[max_steps]; + int sizes[max_steps]; + + const auto baseline = mallinfo().uordblks; + + for (int i = 1; i < max_steps; ++i) { + int size = 1 << i / 2; + if (i % 2) { + size += size / 2; + } + sizes[i] = size; + auto ptr = malloc(size); + escape(ptr); // prevent the compiler from optimizing the malloc away + cost[i] = mallinfo().uordblks; + free(ptr); + } + + cout << "requested\t|\tactual\t|\toverhead\n"; + for (int i = 1; i < max_steps; ++i) { + const auto actual = (cost[i] - baseline); + cout << sizes[i] << "\t\t|\t" << actual << "\t|\t" << (actual - sizes[i]) << '\n'; + } + return 0; +} -- 2.7.4