-1

I am looking for the simplest way to calculate and display the execution time of a function in Qt. The result should be a string/QString in the format mm:ss.

I know I can get an int of milliseconds with QTime but is there a built-in function which does the formatting?

BaCaRoZzo
  • 7,502
  • 6
  • 51
  • 82
isADon
  • 3,433
  • 11
  • 35
  • 49

2 Answers2

4

I just had the same problem in one of my applications. With a small trick it is possible to use the toString method in QTime. It needs to be considered, that toString also takes care of the locale and allows for different time formats. This makes it a non-trivial function to implement.

The following complete code should be enough to explain the basic idea:

#include <QApplication>
#include <QTime>
#include <QTimer>
#include <QEventLoop>
#include <QDebug>

int main(int argc, char** args) {
    QApplication app(argc, args);
    QTime x;
    x.start();
    QTimer wait;
    QEventLoop e;
    QTimer::singleShot(500, &e, &QEventLoop::quit);
    e.exec();
    QTime y(0, 0);
    qDebug() << x.elapsed();
    y=y.addMSecs(x.elapsed());
    qDebug() << y.toString("mm:ss.zzz");
}
Aleph0
  • 5,816
  • 4
  • 29
  • 80
3

If you have the elapsed time in milliseconds (ms), you can print the time in mm:ss format in the following way:

QString out = QString("%1:%2").arg( ms / 60000        , 2, 10, QChar('0'))
                              .arg((ms % 60000) / 1000, 2, 10, QChar('0'));
vahancho
  • 20,808
  • 3
  • 47
  • 55
  • I accepted this answer to early. This doesn't give me the correct format of `mm:ss`. For example if the duration was 7 seconds your code gives me **0:7** instead of **00:07** – isADon Nov 19 '14 at 16:34
  • @isADon once again. Before asking such questions - you may read official documentation about string formatting. – Dmitry Sazonov Nov 20 '14 at 07:17
  • @isADon, I have updated the answer to support the mentioned format. – vahancho Nov 20 '14 at 08:10