google benchmark
首先还是建议大家认真阅读github上的描述,我也是除了很多差错,最后发现还是官网真香
环境:Ubuntu20.04.1
安装编译benchmark
- 安装git和cmake
$ git clone https://github.com/google/benchmark.git
$ cd benchmark
$ cmake -E make_directory "build"
$ cmake -E chdir "build" cmake -DBENCHMARK_DOWNLOAD_DEPENDENCIES=on -DCMAKE_BUILD_TYPE=Release ../
$ cmake --build "build" --config Release
测试benchmark
- 创建demo.cpp文件,如下
#include <benchmark/benchmark.h>
#include <iostream>
#include <string>
using namespace std;
void demo()
{
string str = "hello world";
str.size();
}
static void BM_demo(benchmark::State& state) {
for (auto _ : state)
demo();
}
BENCHMARK(BM_demo);
BENCHMARK_MAIN();
$ g++ demo demo.cpp -std=c++11 -lbenchmark -lpthread
这里也有可能会报错:
/usr/bin/ld: /usr/local/lib/libbenchmark.a(benchmark_runner.cc.o): in function `benchmark::internal::BenchmarkRunner::DoNIterations()':
benchmark_runner.cc:(.text+0x12dd): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
如果报错如上,可以尝试一下:
$ g++ demo demo.cpp -std=c++11 -lbenchmark -pthread
接着你会发现多了一个demo文件,这是刚编译好的
$ ./demo
就可以看到结果了