Add executable to measure malloc overhead.
authorMilian Wolff <mail@milianw.de>
Fri, 26 Feb 2016 20:47:30 +0000 (21:47 +0100)
committerMilian Wolff <mail@milianw.de>
Fri, 26 Feb 2016 20:48:29 +0000 (21:48 +0100)
tests/benchmarks/CMakeLists.txt
tests/benchmarks/measure_malloc_overhead.cpp [new file with mode: 0644]

index 39ea65a..aef438f 100644 (file)
@@ -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 (file)
index 0000000..9d811de
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2016 Milian Wolff <mail@milianw.de>
+ *
+ * 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 <malloc.h>
+#include <unistd.h>
+#include <iostream>
+
+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;
+}