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;
 }
相关推荐
咩咦1 分钟前
C++学习笔记08:指针和引用的区别
c++·学习笔记·指针·引用·指针和引用
洛水水6 分钟前
【力扣100题】34.二叉搜索树中第K小的元素
c++·算法·leetcode
许长安20 分钟前
gRPC Keepalive 机制
c++·经验分享·笔记·rpc
wangjialelele1 小时前
Linux SystemV 消息队列 + 责任链模式:实现客户端消息处理流水线
linux·服务器·c语言·网络·c++·责任链模式
智者知已应修善业1 小时前
51单片机4按键控制共阳LED霓虹灯切换1整体闪烁2流水下3流水上4间隔闪烁】2023-10-27
c++·经验分享·笔记·算法·51单片机
洛水水1 小时前
结构性设计模式详解
c++·设计模式
曦夜日长2 小时前
C++ STL容器string(二):删除与插入、数据查找、自定义输入
java·开发语言·c++
fpcc3 小时前
跟我学C++中级篇—虚函数的优化
c++
智者知已应修善业3 小时前
【51单片机独立按键控制数码管自增自减】2023-10-5
c++·经验分享·笔记·算法·51单片机
ComputerInBook3 小时前
C++中“概念”(concept)之含义
开发语言·c++·概念·concept