how would you benchmark the performance of a function

▼魔方 西西 提交于 2019-11-30 14:42:13

One of the best available opensource solutions is google benchmark . You have to create simple wrappers around code you want to benchmark and link either statically or dynamically with the benchmark lib. It is often useful to have such micro benchmarks compiled near with your code. For inspiration see awesome presentation.

static void BM_F(benchmark::State& state) {
  const auto input1 = state.range_x();
  const auto input2 = state.range_y();

  while (state.KeepRunning()) F(input1, input2);
}

static void BM_D(benchmark::State& state) {
  const auto input1 = state.range_x();
  const auto input2 = state.range_y();

  while (state.KeepRunning()) D(input1, input2);
}

BENCHMARK(BM_F)
    ->ArgPair(1, 10)
    ->ArgPair(10, 100)
    ->ArgPair(100, 1000);

BENCHMARK(BM_D)
    ->ArgPair(1, 10)
    ->ArgPair(10, 100)
    ->ArgPair(100, 1000);

If you want to measure raw CPU cycles, then your only choice is to use direct CPU instructions. For x86 you can use Time Stamp Counter. But you should be aware, that such measuring will not resist any context switches performed by OS or jumping on CPUs. Your only choice in such situation will be to use algo with single flow of execution, remember ID of CPU and TSC value before enter to test function, and check ID of CPU after test function. Then calculating difference between TSC values. You may also setup CPU affinity for your process to stick process to specific CPU.

Another Linux specific possible way to benchmark functions is to use perf tool.

But in any way, any measure will add some error level to the result.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!