c++performancebenchmarkinggoogle-benchmark

Google Benchmark, how to call code only once?


I have a code snippet I need to benchmark composed of 2 parts, first the state needs to be set exactly once, next I need to actually benchmark a function.

My code looks like this:

static void BM_LoopTime(benchmark::State& state) 
{
    MasterEngine engine;
    for (auto _ : state)
    {
        engine.LoopOnce();
    }
}
BENCHMARK(BM_LoopTime);

In my output I am getting:

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Pointer already set                                                             
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Multiple times, which is a custom error message that indicates a very important pointer that should only ever be touched once is trying to be overwritten.

Calling that code multiple times is undefined behaviour in my implementation. How can I call the object initialization exactly once and then tell it to call the loop?


Solution

  • This is a work around that I found that's good enough for my use case but I am still looking for better solutions:

    class MyFixture : public benchmark::Fixture 
    {
    public:
        std::unique_ptr<MasterEngine> engine;
    
        void SetUp(const ::benchmark::State& state) 
        {
            if(engine.get() == nullptr)
                engine = std::make_unique<MasterEngine>();
        }
    
        void TearDown(const ::benchmark::State& state) 
        {
        }
    };