How do I get milliseconds time of execution of a piece of code in Qt/C++?
Asked
Active
Viewed 998 times
3 Answers
7
Use the QTime
class. Start it with .start()
(or .restart()
) and then check the amount of milliseconds passed with .elapsed()
. Naturally, the precision ultimately depends on the underlying OS, although with the major platforms you should have no trouble getting a real millisecond resolution.

Eli Bendersky
- 263,248
- 89
- 350
- 412
4
If you are running on a Windows system, then you can use timer based on the Windows Performace Timers and get microsecond timing.
Intel has a downloadable library at etimer libary. This is a small C routine that is fairly painless to use and gives very good results at the microsecond level

photo_tom
- 7,292
- 14
- 68
- 116
1
If you don't use Qt you can do it with a GetTickCount:
DWORD start = ::GetTickCount(); // start counter
// all the things your program does
DWORD end = ::GetTickCount(); // stop counter
DWORD duration = end - start;
std::cout << "Duration: " << duration << " ms" << std::endl;

Exa
- 4,020
- 7
- 43
- 60
-
GetTickCount() is useless for this kind of thing because it's accuracy is far too low. often 10-50 ms or worse. see: http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx – John Dibling Apr 23 '10 at 12:46
-
Yup, forgot to mention that. Made the same experience when using it. But is the QTime class so much more accurate? At the end, all methods depend on the OS and it's architecture, but it would be nice to know how much faster QTime is. – Exa Apr 23 '10 at 12:59
-
Under Windows, you can use QueryPerformanceCounter() to get high-resolution timing information. This function is not related to GetTickCount() in it's implementation. – John Dibling Apr 23 '10 at 14:49
-
Thanks, I'll have a look at that next time. – Exa Apr 23 '10 at 14:53