在Qt中获取已用时间

我正在寻找相当于Qt GetTickCount()

有些东西可以让我测量一段代码运行的时间,如下所示:

 uint start = GetTickCount(); // do something.. uint timeItTook = GetTickCount() - start; 

有什么build议么?

QTime如何? 根据你的平台,它应该有1毫秒的准确度。 代码看起来像这样:

 QTime myTimer; myTimer.start(); // do something.. int nMilliseconds = myTimer.elapsed(); 

我认为使用QElapsedTimer可能会更好,因为这就是为什么这个类首先存在的原因。 它是用Qt 4.7引入的。 请注意,它也是免疫系统的时钟变化。

用法示例:

 #include <QDebug> #include <QElapsedTimer> ... ... QElapsedTimer timer; timer.start(); slowOperation(); // we want to measure the time of this slowOperation() qDebug() << timer.elapsed(); 

即使第一个答案被接受,其他阅读答案的人也应该考虑sivabudh的build议。
QElapsedTimer也可以用来计算以毫微秒为单位的时间。
代码示例:

 QElapsedTimer timer; qint64 nanoSec; timer.start(); //something happens here nanoSec = timer.nsecsElapsed(); //printing the result(nanoSec) //something else happening here timer.restart(); //some other operation nanoSec = timer.nsecsElapsed(); 

一般策略是多次调用观察的方法。 10个呼叫提供1.5毫秒的精度,100毫秒的0,15毫秒。

如果你想使用QElapsedTimer ,你应该考虑这个类的开销。

例如,下面的代码在我的机器上运行:

 static qint64 time = 0; static int count = 0; QElapsedTimer et; et.start(); time += et.nsecsElapsed(); if (++count % 10000 == 0) qDebug() << "timing:" << (time / count) << "ns/call"; 

给我这个输出:

 timing: 90 ns/call timing: 89 ns/call ... 

你应该为自己衡量这一点,并尊重你的时间开销。

用以前的答案,这里是一个为你做的一切的macros。

 #include <QDebug> #include <QElapsedTimer> #define CONCAT_(x,y) x##y #define CONCAT(x,y) CONCAT_(x,y) #define CHECKTIME(x) \ QElapsedTimer CONCAT(sb_, __LINE__); \ CONCAT(sb_, __LINE__).start(); \ x \ qDebug() << __FUNCTION__ << ":" << __LINE__ << " Elapsed time: " << CONCAT(sb_, __LINE__).elapsed() << " ms."; 

然后你可以简单地使用为:

 CHECKTIME( // any code for (int i=0; i<1000; i++) { timeConsumingFunc(); } ) 

输出:

onSpeedChanged:102已用时间:2毫秒。