googlebenchmark编译安装及基本使用

文档

具体细节参考,官方文档 https://github.com/google/benchmark

安装

$ git clone https://github.com/google/benchmark.git
$ git clone https://github.com/google/googletest.git benchmark/googletest
$ cd benchmark
$ mkdir build && cd build
$ cmake ../
$ make -j4
$ make test
$ sudo make install

示例

#include 

static void BM_StringCreation(benchmark::State& state) {
  for (auto _ : state)
    std::string empty_string;
}
// Register the function as a benchmark
BENCHMARK(BM_StringCreation);

// Define another benchmark
static void BM_StringCopy(benchmark::State& state) {
  std::string x = "hello";
  for (auto _ : state)
    std::string copy(x);
}
BENCHMARK(BM_StringCopy);

BENCHMARK_MAIN();

make 编译

g++ mybenchmark.cc -std=c++11 -isystem benchmark/include \
  -Lbenchmark/build/src -lbenchmark -lpthread -o mybenchmark

cmake 编译

cmake_minimum_required (VERSION 3.5)
project (benchmarklearn)

# C++11支持
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_EXTENSIONS ON)

find_package(benchmark REQUIRED)

add_executable(mybenchmark mybenchmark.cc)

target_link_libraries(mybenchmark benchmark::benchmark)

运行示例程序

./mybenchmark
2020-05-07 09:49:19
Running ./mybenchmark
Run on (32 X 3000 MHz CPU s)
CPU Caches:
  L1 Data 32 KiB (x16)
  L1 Instruction 32 KiB (x16)
  L2 Unified 256 KiB (x16)
  L3 Unified 20480 KiB (x2)
Load Average: 5.54, 5.19, 5.07
***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead.
***WARNING*** Library was built as DEBUG. Timings may be affected.
------------------------------------------------------------
Benchmark                  Time             CPU   Iterations
------------------------------------------------------------
BM_StringCreation       7.66 ns         7.66 ns     71991305
BM_StringCopy           24.8 ns         24.8 ns     28427873

你可能感兴趣的:(benchmark,c++,软件测试)