获取 Qt 中的运行时间

我在找 Qt 和 GetTickCount()的等价物

这样我就可以测量一段代码运行的时间,如下所示:

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

有什么建议吗?

105196 次浏览

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的建议。
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();

如果您想使用 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
...

您应该自己测量这一点,并尊重您的计时开销。

展开前面的答案,这里有一个宏,它可以为您做任何事情。

#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 ms。