memorymanager icon indicating copy to clipboard operation
memorymanager copied to clipboard

Benchmark Causes Segfault

Open markovejnovic opened this issue 3 months ago • 0 comments

Unfortunately this code crashes in the multi-threading case. I haven't managed to determine why exactly. Hopefully you'll find this helpful! :)

#include <benchmark/benchmark.h>
#include <vector>
#include <random>
#include <thread>
#include <algorithm>

static void BM_Multithreaded_LocalAlloc(benchmark::State& state) {
  struct Small { uint64_t data; };
  const int allocs_per_thread = 1000;

  for (auto _ : state) {
    std::vector<Small*> ptrs;
    ptrs.reserve(allocs_per_thread);

    // Each thread allocates and deallocates its own memory
    for (int i = 0; i < allocs_per_thread; ++i) {
      ptrs.push_back(new Small);
    }

    benchmark::DoNotOptimize(ptrs.data());

    for (auto ptr : ptrs) {
      delete ptr;
    }
  }
  state.SetItemsProcessed(state.iterations() * allocs_per_thread);
}
BENCHMARK(BM_Multithreaded_LocalAlloc)->Threads(1)->Threads(2)->Threads(4)->Threads(8);

BENCHMARK_MAIN();

This code was built with g++ -Wall -O2 -pthread -march=native -std=c++11 -lbenchmark -lpthread benchmark.cpp MemoryManager.cpp.

markovejnovic avatar Oct 28 '25 20:10 markovejnovic