benchmark

好久没写了

简单写一篇吧

最近在用benchmark,看了下wiki

In all cases, the number of iterations for which the benchmark is run is

governed by the amount of time the benchmark takes. Concretely, the number of

iterations is at least one, not more than 1e9, until CPU time is greater than

the minimum time, or the wallclock time is 5x minimum time. The minimum time is

set per benchmark by calling `MinTime` on the registered benchmark object.

这段是关于统计时间的,我简单思考了下,猜测了基本实现

然后又看了下源码,发现和想的大差不差吧

时间的统计

先获取real time

再获取cputime

获取方法如下:

cpp 复制代码
 inline double ChronoClockNow() {
    typedef ChooseClockType::type ClockType;
    using FpSeconds = std::chrono::duration<double, std::chrono::seconds::period>;
    return FpSeconds(ClockType::now().time_since_epoch()).count();
  }

 double ThreadCPUUsage() {
   struct timespec ts;
   if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) == 0) return MakeTime(ts);
   DiagnoseAndExit("clock_gettime(CLOCK_THREAD_CPUTIME_ID, ...) failed");

所以这个统计时间,要注意,会包含获取cpu时间的overhead

循环

cpp 复制代码
for (;;) {
     b.Setup();
     i = DoNIterations();
     b.Teardown();

通过这个应该可以更清楚理解,使用方法介绍的 Setup/Teardown了

这里会一直循环下去,每一次操作都会统计时间,直到触发下面条件

cpp 复制代码
bool BenchmarkRunner::ShouldReportIterationResults(
     const IterationResults& i) const {
   // Determine if this run should be reported;
   // Either it has run for a sufficient amount of time
   // or because an error was reported.
   bool b_flag = i.results.skipped_ ||
          i.iters >= kMaxIterations ||  // Too many iterations already.
          i.seconds >=
              GetMinTimeToApply() ||  // The elapsed time is large enough.
          // CPU time is specified but the elapsed real time greatly exceeds
          // the minimum time.
          // Note that user provided timers are except from this test.
          ((i.results.real_time_used >= 5 * GetMinTimeToApply()) &&
           !b.use_manual_time());
   return b_flag;
 }
相关推荐
枕星而眠5 小时前
【数据结构】红黑树入门指南
运维·数据结构·c++·后端
2601_949817725 小时前
C++指针与引用深度精讲:底层原理、差异对比与高阶实战陷阱
java·jvm·c++
烟锁池塘柳07 小时前
【C/C++】解决C++控制台输出中文乱码问题
c语言·开发语言·c++
zh路西法7 小时前
【10天速通Navigation2】(九):LQR最优控制器的原理推导与Nav2插件实现
c++·ros2·最优控制·lqr·navigation2
粘稠的浆糊8 小时前
[AtCoder - abc465_d ]X to Y题解
数据结构·c++·算法
誰能久伴不乏8 小时前
C++11 随机数生成——告别 rand()
开发语言·c++
KouFiee8 小时前
同名隐藏基础
开发语言·c++
从零开始的代码生活_8 小时前
C++ string 详解:常用接口、字符串算法与深拷贝实现
开发语言·c++·后端·学习·算法
aaPIXa62210 小时前
C++ 质量前置检查:clang-format 与 clang-tidy 实践指南
开发语言·c++
余额瞒着我当琳10 小时前
C++ 基础核心概念精讲:引用、内联与 nullptr
java·开发语言·c++