我正在寻找 Qt 中的等价物GetTickCount()
可以让我测量一段代码运行所需的时间,如下所示:
uint start = GetTickCount();
// do something..
uint timeItTook = GetTickCount() - start;
有什么建议么?
我认为使用它可能会更好,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();
怎么样QTime
?根据您的平台,它应该具有 1 毫秒的精度。代码看起来像这样:
QTime myTimer;
myTimer.start();
// do something..
int nMilliseconds = myTimer.elapsed();
即使第一个答案被接受,其他阅读答案的人也应该考虑sivabudh
的建议。
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();
扩展之前的答案,这是一个可以为您完成所有工作的宏。
#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 毫秒。
如果你想使用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
...
您应该自己衡量这一点,并尊重您的时间开销。