Google Benchmarking in C++

Google Benchmarking in C++

Learning through the simple example

Install Google Benchmarking in Ubuntu:

sudo apt-get update
sudo apt-get install -y git cmake build-essential libbenchmark-dev
git clone https://github.com/google/benchmark.git
cd benchmark
git clone https://github.com/google/googletest.git
mkdir build
cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
make
sudo make install

With above commands the google benchmark and its dependency of googletest is installed.

Now create the CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(MyBenchmark)

find_package(benchmark REQUIRED)
add_executable(my_benchmark main.cpp)
target_link_libraries(my_benchmark benchmark::benchmark)

Now checking Function1 & Function2 performance:

#include <benchmark/benchmark.h>

// Function1: Simple loop that performs addition
void Function1() {
    volatile int sum = 0;
    for (int i = 0; i < 1000; ++i) {
        sum += i;
    }
}

// Function2: Simple loop that performs multiplication
void Function2() {
    volatile int product = 1;
    for (int i = 1; i < 1000; ++i) {
        product *= i;
    }
}

// Benchmark for Function1
static void BM_Function1(benchmark::State& state) {
    for (auto _ : state) {
        Function1();
    }
}

// Benchmark for Function2
static void BM_Function2(benchmark::State& state) {
    for (auto _ : state) {
        Function2();
    }
}

// Register the functions as benchmarks
BENCHMARK(BM_Function1);
BENCHMARK(BM_Function2);

// Main function to run the benchmarks
BENCHMARK_MAIN();

Output:

2024-05-18T16:43:07+05:30
Running /home/home/C++/build-b2w-Desktop-Debug/my_benchmark
Run on (4 X 3100 MHz CPU s)
CPU Caches:
  L1 Data 32 KiB (x2)
  L1 Instruction 32 KiB (x2)
  L2 Unified 256 KiB (x2)
  L3 Unified 3072 KiB (x1)
Load Average: 0.52, 0.87, 1.29
***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead.
-------------------------------------------------------
Benchmark             Time             CPU   Iterations
-------------------------------------------------------
BM_Function1       1930 ns         1924 ns       362582
BM_Function2       2411 ns         2412 ns       290077

Process exited with code: 0