shoosh
shoosh

Reputation: 78914

Get elapsed time in Qt

I'm looking for the equivalent in Qt to GetTickCount()

Something that will allow me to measure the time it takes for a segment of code to run as in:

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

any suggestions?

Upvotes: 83

Views: 116753

Answers (5)

Lilian A. Moraru
Lilian A. Moraru

Reputation: 1066

Even if the first answer was accepted, the rest of the people who read the answers should consider sivabudh's suggestion.
QElapsedTimer can also be used to calculate the time in nanoseconds.
Code example:

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();

Upvotes: 42

Damien
Damien

Reputation: 1552

Expending the previous answers, here is a macro that does everything for you.

#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.";

And then you can simple use as:

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

output:

onSpeedChanged : 102 Elapsed time: 2 ms.

Upvotes: 3

Dusty Campbell
Dusty Campbell

Reputation: 3156

How about QTime? Depending on your platform it should have 1 millisecond accuracy. Code would look something like this:

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

Upvotes: 95

Oliver Hoffmann
Oliver Hoffmann

Reputation: 140

If you want to use QElapsedTimer, you should consider the overhead of this class.

For example, the following code run on my machine:

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";

gives me this output:

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

You should measure this for yourself and respect the overhead for your timing.

Upvotes: 2

sivabudh
sivabudh

Reputation: 32635

I think it's probably better to use QElapsedTimer since that is why the class exists in the first place. It was introduced with Qt 4.7. Note that it is also immuned to system's clock time change.

Example usage:

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

Upvotes: 145

Related Questions