我正在寻找Qt中的等价物来 GetTickCount()

允许我测量一段代码运行时间的东西,如:

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

有什么建议吗?

有帮助吗?

解决方案

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毫秒。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top