How do I benchmark code with Google Benchmark?

Google Benchmark is a powerful library for benchmarking C++ code, allowing developers to measure the execution time of their functions accurately. This tool provides detailed insights into performance and helps identify bottlenecks in the code.

Google Benchmark, C++ benchmarking, performance measurement, code optimization, profiling C++ code

This guide will walk you through how to set up Google Benchmark in your C++ project, create a simple benchmark example, and execute it to measure performance.

#include <benchmark/benchmark.h>

// A simple function to benchmark
static void BM_Square(benchmark::State &state) {
    for (auto _ : state) {
        // Compute square of a number
        benchmark::DoNotOptimize(sqrt(123.456));
    }
}

// Register the benchmark
BENCHMARK(BM_Square);

BENCHMARK_MAIN();

Google Benchmark C++ benchmarking performance measurement code optimization profiling C++ code