Getting milliseconds accuracy current time in Qt

20.9k Views Asked by At

Qt documentation about QTime::currentTime() says :

Note that the accuracy depends on the accuracy of the underlying operating system; not all systems provide 1-millisecond accuracy.

But is there any way to get this time with milliseconds accuracy in windows 7?

4

There are 4 best solutions below

0
On BEST ANSWER

You can use QDateTime class and convert the current time with the appropriate format:

QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss,zzz")

where 'z' corresponds to miliseconds accuracy.

0
On

Timer resolution may vary on different platforms and readings may not be accurate. If you need to get high-resolution, accurate timestamps on Windows 7, it provides QPC API:

https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408%28v=vs.85%29.aspx

GetSystemTimePreciseAsFileTime is claimed to provide system time with <1us resolution.

But that's only about accurate timestamp. If you need to actually do something with 1 ms latency (ex. handle an event), you need a RTOS, not a desktop clunker.

2
On

One common way would be to scale up whatever you are doing and do it 10-100 times in a row, that way you would be able get a more accurate time reading of whatever you are doing, by dividing the result by 10-100.

But getting millisecond precise readings of your time is pretty much useless because you don't have 100% of the cpu time, which means that your readings will have much greater variance than just 1 millisecond if the OS gives another process computing time while you are doing your actions.

0
On

you can use the functionality provided by time.h header file in C/C++.

#include <time.h> 
clock_t start, end; 
double cpu_time_used; 
int main()
{
    start = clock();
    /* Do the work. */ 
    end = clock(); 
    cpu_time_used = ((double)(end-start)/ CLOCKS_PER_SEC);
}