提问者:小点点

Google benchmark代码设置


给定以下代码

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

static void BM_foo(benchmark::State& state) {
  std::cout << "Foo "<< std::endl;
  for (auto _: state) {
    std::cout <<  state.iterations()  << " In loop " <<std::endl;
  }
}

BENCHMARK(BM_foo);

BENCHMARK_MAIN();

我以为std::cout<<;“foo”<<;std::endl;将只执行一次,但在我的测试期间,它运行了7次。

所以我的问题是:

在我的真实案例中,我想在多线程场景中运行一些存储引擎相关的代码。步骤如下:

我有以下伪代码,但我认为它至少2个问题。

DBConnection* conn; // global variables, so that each thread can run access it.

static void BM_db_insert(benchmark::State& state) {
  if (state.thread_index == 0) {
    # only let 1 thread to setup the DBConnections
    conn = openDBConn();
  }
  DBSession* session = conn.openSession();
  for (auto _ : state) {
    session.insertOp(id, ..); 
  }
  session.close();
  if (state.thread_index == 0) {
    conn.close();
  }
}

问题:

所以我有4个问题分为两部分,如果你对我的代码有更多的建议,那会更好。谢啦!


共1个答案

匿名用户

>

如果需要的话,您需要自己跟踪迭代计数。然而,如果你这样做了,那么也许你所做的基准测试并不是与迭代次数无关的,迭代次数是动态确定的。如果您想要固定的迭代次数,您应该查看

>

我会在每个线程上添加一个显式的等待连接的设置。在打开会话之前,在循环中执行某种类型的