c++stdvectorgoogle-benchmark

cannot create std::vector larger than max_size() for size below max_size


I am running google benchmark for some basic cache testing and I get the following error:

terminate called after throwing an instance of 'std::length_error'

what():  cannot create std::vector larger than max_size()

However, I am printing the max_size and the actual size (see below) and while the max_size equals 2^60-1 it breaks at 2^28. What am I missing?

The benchmark code is below. The code is compiled using Clang 11 with c++20.

static void bm_std_vector_in_cache_double(benchmark::State& state)
{
  auto constexpr d{3.1415};

  auto const bytes = (2 << state.range(0)) * 1024;
  auto data = std::vector<double>(bytes / sizeof(double), d);
  std::cout << data.max_size() << '\n';
  std::cout << data.size() << '\n';
  for (auto _ : state){
      auto sum = 0.0;
      for(auto j = 0; j < data.size(); ++j)
        benchmark::DoNotOptimize(sum += data[j] * data[j]);
    }

  state.SetBytesProcessed(state.iterations() * data.size());
}

BENCHMARK(bm_std_vector_in_cache_double)->DenseRange(1, 20);

Solution

  • The issue here was that the type of bytes was an int.

    auto const bytes = (2 << state.range(0)) * 1024;
    

    changing to

    auto const bytes = (2 << state.range(0)) * 1024L;
    

    changes it to a long allowing for longer vectors and even better better unsigned long long:

    auto const bytes = (2 << state.range(0)) * 1024ULL;