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;
 }
相关推荐
ShineWinsu4 小时前
对于C++:auto_ptr、unique_ptr、shared_ptr的模拟实现
c++·面试·笔试·智能指针·unique_ptr·shared_ptr·auto_ptr
XLYcmy6 小时前
京东 算法实习一面 下+手撕
c++·python·llm·概率论·数据处理·训练·codebert
反转180度7 小时前
Qt 6 + C++17 实现 SFTP 批量部署:工业设备运维工具实战解析
运维·c++·qt
码匠许师傅8 小时前
【C++ 面试真题】聊聊 C++ 的多继承与虚继承
开发语言·c++·面试
有点。10 小时前
C++认识数
开发语言·c++
2023自学中10 小时前
Qt 简易聊天室(第二篇),单线程 改为 多线程,方便后续增加文件传输功能
c++·qt
Tyler_TXZ11 小时前
C++C语言之——二叉树
c语言·开发语言·数据结构·c++·二叉树
有点。12 小时前
C++二叉树二(练习题)
数据结构·c++·算法·图论
不会代码的小猴12 小时前
C++新增关键字
开发语言·c++·笔记
liulilittle13 小时前
并发与内存安全术语:定义、分类与关联
c++·安全·并发·术语