PDA

View Full Version : Simple stopwatch to time some code?



te777
23rd June 2015, 00:56
What's the simplest way to measure the amount of time a piece of code takes using QTimer? I just want to time the code and convert it to text to output to a message box. Thanks in advance for any help.

jefftee
23rd June 2015, 01:16
QTime::start() or QTime::restart() followed by QTime::elapsed()

te777
23rd June 2015, 02:41
Thanks. That worked.

Added after 58 minutes:

This is what I used:

Header file for class

myclass.h


#include <QMessageBox>
#include <QTime>

QTime t;
double time;
QMessageBox msgBox;


In myclass.cpp file for class


void myclass::Method1(void)
{

// Message Box here to introduce method

time = 0.0
t.start();

// Code to time here

time += ((double) t.elapsed())/1000.0;


}

void myclass::Method2(void)
{

// Message Box here to introduce method

t.restart();

// Code to time here

time += ((double) t.elapsed())/1000.0;

}

void myclass::Method3(void)
{

// Message Box here to introduce method

t.restart();

// Code to time here

time += ((double) t.elapsed())/1000.0;

}

void myclass::Method4(void)
{

QString Temp;

// Message Box here to introduce method

t.restart();

// Code to time here

time += ((double) t.elapsed())/1000.0;

Temp = "Seconds = " + QString::number(time);

msgBox.setText(Temp);
msgBox.exec();


}

Lesiok
23rd June 2015, 09:03
Use QElapsedTimer. It is better for calculate elapsed time.

te777
23rd June 2015, 13:44
Thanks. I'll look into it.

Added after 43 minutes:

I tried QElapsedTimer. It seems to have some overhead associated with use of the class. But very minor. The difference is not that much. But QTime seemed to give me a little bit more quicker execution time. I measured the number crunching code of 4 methods (3 times with QTime and 3 with QElapsedTimer) and ended up with the following results:

QElapsedTimer

8.06 s
8.028 s
8.05 s

Average = 8.046 s

QTime

8.013 s
8.021 s
8.013 s

Average = 8.016 s

It seems the use of QTime ended up with a little bit more quicker execution time. It would probably be more significant for more time consuming processes. The StackOverflow thread following seems to cover the use of QElapsedTime pretty well: http://stackoverflow.com/questions/244646/get-elapsed-time-in-qt