如何从steady_clock返回经过的时间作为原始数据类型(double)

How To Return Elapsed Time From steady_clock as a Primitive Data Type (double)

本文关键字:原始 数据类型 double 时间 steady clock 经过 返回      更新时间:2023-10-16

首先,我要说的是,我昨天才开始使用这个库,所以我对它的理解仍然相当基础。我试图捕捉我正在创建的视觉处理程序的FPS,并使用chrono库将其输出到屏幕。在我的例子中,我需要将启动steady_clock后所花费的时间强制转换为double(或者其他一些可以视为double类型的数值类型定义)。我查看了参考文档,并尝试使用duration_casttime_point_cast函数,但这两个函数似乎都不是我想要的。

我的问题是;是否有办法简单地将时钟当前状态的数值(以秒为单位)转换为原始数据类型?

像这样:

#include <chrono>
#include <iostream>
#include <thread>
int main()
{
  using namespace std::literals;
  // measure time now
  auto start = std::chrono::system_clock::now();
  // wait some time
  std::this_thread::sleep_for(1s);
  // measure time again
  auto end = std::chrono::system_clock::now();
  // define a double-precision representation of seconds
  using fsecs = std::chrono::duration<double, std::chrono::seconds::period>;
  // convert from clock's duration type
  auto as_fseconds = std::chrono::duration_cast<fsecs>(end - start);
  // display as decimal seconds
  std::cout << "duration was " << as_fseconds.count() << "sn";
}

示例输出:

duration was 1.00006s

可以使用duration::count函数。

例如,您可以获得以毫秒为单位的持续时间,然后将该计数除以1000.0,得到作为double的秒数。