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 <benchmark/benchmark.h>

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章