【问题标题】:how can i get a difference between two Time interval's in micro and nano seconds using c++如何使用c ++获得两个时间间隔(以微秒和纳秒为单位)之间的差异
【发布时间】:2017-06-24 06:33:40
【问题描述】:

我正在做一个项目,因为我需要检查两次之间的时差,以毫秒为单位获得时差,但现在我想要以微秒和纳秒为单位的时差来获得准确的时差

我的代码:

QDateTime oStartTime = QDateTime::currentDateTime();  

// some operetions            //the difference is in micro and nano seconds differ 

QDateTime oEndTime = QDateTime::currentDateTime();  
quint64 elapsed = oStartTime.daysTo(oEndTime)*1000*60*60*24 + oStartTime.time().msecsTo(oEndTime.time());

上面的代码只会给我毫秒的时间差异。我还需要微秒和纳秒。有什么建议如何获得微秒和纳秒的时间吗?

【问题讨论】:

  • std::chrono ,就是你在找的东西。 See here for example
  • chrono 不支持我使用 QT4.3.2 版本和 Visual Studio 2005 编译,所以可以得到微秒和纳秒
  • 尝试 GetSystemTimeAsFileTime(LPFILETIME) ,其中 FILETIME 结构包含一个 64 位值,表示 100 纳秒时间戳的数量。

标签: c++ qt


【解决方案1】:

QT 提供QElapsedTimer 使用系统的高分辨率计数器获取时差(参见clock types)。

【讨论】:

  • 但是我的 QT 是 4.3.2 版本,它不支持 QElapsedTimer ,所以请你给我建议任何其他方法来获得微秒和纳秒的时间差
  • 您可以使用本机计时器。见this thread
【解决方案2】:

C++11 提供chrono 库来处理时间。它具有专门设计用于计算时间间隔的 stable_clock。还有持续时间模板类的微秒和纳秒实例化。

#include <chrono> // C++11
#include <iostream>

using namespace std::chrono;

int main()
{
    steady_clock::time_point tp1 = steady_clock::now();

    std::cout<<"some time to spend..."<<std::endl;
    steady_clock::time_point tp2 = steady_clock::now();

    nanoseconds spent_time = duration_cast<nanoseconds>(tp2 - tp1);
    std::cout<<"It took "<<spent_time.count()<<" nanoseconds."<<std::endl;

    return 0;
}

标准输出:

some time to spend...
It took 207960 nanoseconds.

【讨论】:

  • 收到此类错误,似乎不支持chrono 致命错误C1083:无法打开包含文件:'chrono':没有这样的文件或目录
  • @SrikanthTogara 为您的编译器启用 C++11 以访问 chrono
猜你喜欢
  • 2020-09-29
  • 1970-01-01
  • 2015-10-09
  • 2015-10-17
  • 2021-08-12
  • 2014-06-24
  • 2014-02-26
  • 2012-12-03
  • 2012-09-13
相关资源
最近更新 更多