qtqelapsedtimer

How to stop QElapsedTimer?


    QElapsedTimer timer;
    timer.start();

    slowOperation1();

    qDebug() << "The slow operation took" << timer.elapsed() << "milliseconds";

http://doc.qt.io/qt-5/qelapsedtimer.html#invalidate

After qDebug() I would want to stop this timer. I can't see a stop function there, nor a single shot property.

What's the way out?


Solution

  • You can't stop QElapsedTimer, because there is no timer. When you call method start(), QElapsedTimer saves the current time.

    From qelapsedtimer_generic.cpp

    void QElapsedTimer::start() Q_DECL_NOTHROW
    {
        restart();
    }
    
    qint64 QElapsedTimer::restart() Q_DECL_NOTHROW
    {
        qint64 old = t1;
        t1 = QDateTime::currentMSecsSinceEpoch();
        t2 = 0;
        return t1 - old;
    }
    

    When elapsed, it gets current time again, and calculate difference.

    qint64 QElapsedTimer::elapsed() const Q_DECL_NOTHROW
    {
        return QDateTime::currentMSecsSinceEpoch() - t1;
    }
    

    P.S. Specific realization is platform dependent: Windows, Unix, Mac