File indexing completed on 2024-10-13 13:23:09
0001 /* 0002 SPDX-FileCopyrightText: 2015-2017 Milian Wolff <mail@milianw.de> 0003 0004 SPDX-License-Identifier: LGPL-2.1-or-later 0005 */ 0006 0007 #ifndef BENCH_POINTERS 0008 #define BENCH_POINTERS 0009 0010 #include <algorithm> 0011 #include <cstdint> 0012 #include <iostream> 0013 #include <random> 0014 #include <vector> 0015 0016 #include <malloc.h> 0017 0018 #include "src/util/indices.h" 0019 0020 template <typename Map> 0021 void benchPointers() 0022 { 0023 auto randGenerator = std::mt19937(0); 0024 0025 uint32_t matches = 0; 0026 constexpr uint32_t NUM_POINTERS = 10000000; 0027 { 0028 std::vector<uint64_t> pointers(NUM_POINTERS); 0029 const auto baseline = mallinfo2().uordblks; 0030 std::cerr << "allocated vector: \t" << baseline << std::endl; 0031 for (uint32_t i = 0; i < NUM_POINTERS; ++i) { 0032 pointers[i] = reinterpret_cast<uint64_t>(malloc(1)); 0033 } 0034 const auto allocated = (mallinfo2().uordblks - baseline); 0035 std::cerr << "allocated input pointers:\t" << allocated << std::endl; 0036 for (auto ptr : pointers) { 0037 free(reinterpret_cast<void*>(ptr)); 0038 } 0039 std::cerr << "freed input pointers: \t" << (mallinfo2().uordblks - baseline) << std::endl; 0040 srand(0); 0041 std::shuffle(pointers.begin(), pointers.end(), randGenerator); 0042 malloc_trim(0); 0043 std::cerr << "begin actual benchmark: \t" << (mallinfo2().uordblks - baseline) << std::endl; 0044 0045 { 0046 Map map; 0047 for (auto ptr : pointers) { 0048 AllocationInfoIndex index; 0049 index.index = static_cast<uint32_t>(ptr); 0050 map.addPointer(ptr, index); 0051 } 0052 0053 const auto added = mallinfo2().uordblks - baseline; 0054 std::cerr << "pointers added: \t" << added << " (" << (float(added) * 100.f / allocated) 0055 << "% overhead)" << std::endl; 0056 0057 std::shuffle(pointers.begin(), pointers.end(), randGenerator); 0058 for (auto ptr : pointers) { 0059 AllocationInfoIndex index; 0060 index.index = static_cast<uint32_t>(ptr); 0061 auto allocation = map.takePointer(ptr); 0062 if (allocation.second && allocation.first == index) { 0063 ++matches; 0064 } 0065 } 0066 0067 std::cerr << "pointers removed: \t" << mallinfo2().uordblks << std::endl; 0068 malloc_trim(0); 0069 std::cerr << "trimmed: \t" << mallinfo2().uordblks << std::endl; 0070 } 0071 } 0072 if (matches != NUM_POINTERS) { 0073 std::cerr << "FAILED!"; 0074 abort(); 0075 } 0076 } 0077 0078 #endif