2

我有这个 Google Benchmark 使用的最小示例。奇怪的是“42”被打印了很多次(4),而不仅仅是一次。我知道图书馆必须多次运行才能获得统计信息,但我认为这是由 statie-loop 本身处理的。

这是一个更复杂的事情的最小示例,我想打印(在循环外)结果以验证同一函数的不同实现是否会给出相同的结果。

#include <benchmark/benchmark.h>
#include<iostream>

#include <thread> //sleep for

int SomeFunction(){
    using namespace std::chrono_literals;
    std::this_thread::sleep_for(10ms);
    return 42;
}

static void BM_SomeFunction(benchmark::State& state) {
  // Perform setup here
  int result = -1;
  for (auto _ : state) {
    // This code gets timed
    result = SomeFunction();
    benchmark::DoNotOptimize(result);
  }
  std::cout<< result <<std::endl;
}
// Register the function as a benchmark
BENCHMARK(BM_SomeFunction);

// Run the benchmark
BENCHMARK_MAIN();

输出:(42打印4次,为什么不止一次,为什么4?)

Running ./a.out
Run on (12 X 4600 MHz CPU s)
CPU Caches:
  L1 Data 32 KiB (x6)
  L1 Instruction 32 KiB (x6)
  L2 Unified 256 KiB (x6)
  L3 Unified 12288 KiB (x1)
Load Average: 0.30, 0.65, 0.79
42
42
42
42
----------------------------------------------------------
Benchmark                Time             CPU   Iterations
----------------------------------------------------------
BM_SomeFunction   10243011 ns        11051 ns         1000

我还能如何测试(至少在视觉上)不同的基准测试块给出相同的答案?

4

0 回答 0