0

I am working on a project, in that i need to check the time difference, between two times, am getting time difference in milliseconds , but now i want the time difference in micro and nano seconds to get exact time difference

my code :

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());

Above code will give me only milliseconds difference in time . I also need the micro & nano seconds. Any suggestion how to get time with micro & nano seconds also?

Srikanth Togara
  • 49
  • 2
  • 11
  • std::chrono , is what you are looking. [See here for example](http://stackoverflow.com/questions/9089842/c-chrono-system-time-in-milliseconds-time-operations/31521226#31521226) – ban Feb 07 '17 at 06:11
  • chrono is not supporting to my using QT4.3.2 version and visual studio 2005 compiles , so is it possible to get micro and nano seconds – Srikanth Togara Feb 07 '17 at 08:47
  • try GetSystemTimeAsFileTime(LPFILETIME) , where FILETIME structure Contains a 64-bit value representing the number of 100-nanosecond time-stamp. – ban Feb 07 '17 at 10:25

2 Answers2

2

C++11 provides chrono library to work with time. It has steady_clock specially designed to calculate time intervals. Also there's microseconds and nanoseconds instantiations of duration template class.

#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;
}

stdout:

some time to spend...
It took 207960 nanoseconds.
slavust
  • 138
  • 1
  • 1
  • 7
0

QT provides QElapsedTimer for getting time differences by using the system's high-resolution counter (see clock types).

Youka
  • 2,646
  • 21
  • 33
  • but my QT is 4.3.2 version it does't support QElapsedTimer , so will you please suggest me any alternate ways to get micro and nano seconds difference in time – Srikanth Togara Feb 07 '17 at 07:25
  • You could use the native timer. See [this thread](http://stackoverflow.com/questions/5404277/porting-clock-gettime-to-windows). – Youka Feb 08 '17 at 12:47