如何从steady_clock返回经过的时间作为基元数据类型(双)

时间:2016-10-01 22:47:11

标签: c++ chrono

首先,我要说我昨天刚开始使用这个库,所以我对它的理解仍然相当基础。我尝试捕获视觉处理程序的FPS,我使用 chrono 库创建并输出到屏幕。在我的情况下,我需要将我开始 steady_clock 之后经过的时间转换为 double (或者其他一些我可以像对待一样处理的数字typedef)。我查看了参考文档并尝试使用 duration_cast time_point_cast 函数,但这些似乎都不是我想要的。

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

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:3)

像这样:

#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() << "s\n";
}

示例输出:

duration was 1.00006s

答案 1 :(得分:1)

您可以使用duration::count功能执行此操作。

例如,您可以在毫秒数内获得持续时间,然后将the count除以1000.0,以获得double的秒数。