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;
 }
相关推荐
啊森要自信2 小时前
【QT】常⽤控件详解(四)常用显示类控件类 Label && LCDNumber && ProgressBar && Calendar Widget
开发语言·数据库·c++·qt·qt6.3
幽迷狂6 小时前
AFSIM入门教程03.03:更新所有依赖库版本
c++·qt·仿真·osgearth·osg·军事·afsim
勇闯逆流河6 小时前
【C++】Stack and Queue and Functor
开发语言·c++
TravisBytes9 小时前
gRPC C++ 从 0 到 1 → 到线上:**超详细** 环境搭建、编码范式、性能调优与 DevOps 全攻略
开发语言·c++·devops
CUC-MenG11 小时前
2025牛客多校第六场 D.漂亮矩阵 K.最大gcd C.栈 L.最小括号串 个人题解
c语言·c++·算法·矩阵
2401_8762213412 小时前
Tasks and Deadlines(Sorting and Searching)
c++·算法
啊阿狸不会拉杆14 小时前
《算法导论》第 2 章 - 算法基础
数据结构·c++·算法·排序算法
啊阿狸不会拉杆14 小时前
《算法导论》第 4 章 - 分治策略
开发语言·数据结构·c++·算法·排序算法
白葵新14 小时前
C#案例实战
c++·python·算法·计算机视觉·c#
一只余弦函数14 小时前
《C++》继承完全指南:从入门到精通
c++