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;
 }
相关推荐
特种加菲猫13 分钟前
多态:让代码拥有“千变万化”的能力
开发语言·c++
莫等闲-1 小时前
代码随想录一刷记录Day44——leetcode1143.最长公共子序列 53. 最大子序和
数据结构·c++·算法·leetcode·动态规划
承渊政道1 小时前
【动态规划算法】(背包问题经典模型与解题套路)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
weixin_421725261 小时前
2026年C/C++/C#全解析:底层语言的进化与场景抉择,选错直接掉队
c语言·c++·c·编程语言·技术选择
我头发多我先学2 小时前
C++ 红黑树:从规则到实现,手把手带你写一棵红黑树
数据结构·c++·算法
lzh200409192 小时前
深入学习Linux进程间通信:解析消息队列
linux·c++
水饺编程2 小时前
第5章,[标签 Win32] :设备的尺寸(三)
c语言·c++·windows·visual studio
Cando学算法2 小时前
中位数定理:到所有点的距离之和最小的点就是中位数
c++·算法·学习方法
HZY1618yzh2 小时前
洛谷题解:P16304 [蓝桥杯 2026 省 Java C 组] 抽奖活动
java·c++·算法·蓝桥杯
智者知已应修善业2 小时前
【51单片机从奇数始再转偶数逐一点亮并循环】2023-9-8
c++·经验分享·笔记·算法·51单片机