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;
 }
相关推荐
无敌昊哥战神4 分钟前
【算法与数据结构】深入浅出回溯算法:理论基础与核心模板(C/C++与Python三语解析)
c语言·数据结构·c++·笔记·python·算法
zore_c5 分钟前
【C++】基础语法(命名空间、引用、缺省以及输入输出)
c语言·开发语言·数据结构·c++·经验分享·笔记
草莓熊Lotso9 分钟前
Linux 线程深度剖析:线程 ID 本质、地址空间布局与 pthread 源码全解
android·linux·运维·服务器·数据库·c++
沐雪轻挽萤10 分钟前
2. C++17新特性-结构化绑定 (Structured Bindings)
java·开发语言·c++
Robot_Nav19 分钟前
ThetaStar全局规划算法纯C++控制器详解
开发语言·c++·lazy_theta_star
草莓熊Lotso1 小时前
MySQL 从入门到实战:视图特性 + 用户权限管理全解
linux·运维·服务器·数据库·c++·mysql
Q741_1471 小时前
每日一题 力扣 1848. 到目标元素的最小距离 模拟 C++题解
c++·算法·leetcode·模拟
W23035765739 小时前
经典算法:最长上升子序列(LIS)深度解析 C++ 实现
开发语言·c++·算法
.Ashy.9 小时前
2026.4.11 蓝桥杯软件类C/C++ G组山东省赛 小记
c语言·c++·蓝桥杯
minji...10 小时前
Linux 线程同步与互斥(三) 生产者消费者模型,基于阻塞队列的生产者消费者模型的代码实现
linux·运维·服务器·开发语言·网络·c++·算法