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 分钟前
Visual Studio 软件操作:添加附加依赖项
c语言·c++·windows·visual studio
-To be number.wan23 分钟前
C++ 进阶技巧:如何让 cout << 自定义对象 正常输出?
开发语言·c++
序属秋秋秋1 小时前
《Linux系统编程之进程控制》【进程创建 + 进程终止】
linux·c语言·c++·操作系统·进程·进程创建·进程终止
上天_去_做颗惺星 EVE_BLUE1 小时前
C++学习:学生成绩管理系统
c语言·开发语言·数据结构·c++·学习
John_ToDebug1 小时前
Chromium WebUI 定制实践:从 C++ 注入到 JS 安全展示全链路解析
javascript·c++·chrome
水饺编程1 小时前
开源项目介绍:VirtuaNES 模拟器
c语言·c++·windows·visual studio
十五年专注C++开发2 小时前
CMake进阶:find_package使用总结
开发语言·c++·cmake·跨平台编译
闻缺陷则喜何志丹2 小时前
【计算几何】平面凸包
c++·数学·扫描线·凸包·单调性·上凸包·下凸包
-To be number.wan2 小时前
C++ 运算符重载入门:让“+”也能为自定义类型服务!
开发语言·c++
汉克老师2 小时前
GESP2025年12月认证C++一级真题与解析(编程题1 (小杨的爱心快递))
c++·数据类型·选择结构·格式输出