QTime::elapsed() behavior



  • While reviewing some code, I came across the following:

    QString FooBar::getNextNotification(int timeOut)
    {
        QTime startTime = QTime::currentTime();
        QTime::currentTime();
    
        while (startTime.elapsed() < timeOut)
        {
            ...
        }
        ...
    }
    

    I have two questions about this function:

    1. The documentation at http://doc.qt.io/archives/qt-4.8/qtime.html#elapsed writes "Returns the number of milliseconds that have elapsed since the last time start() or restart() was called." Note however that we are not calling start() or restart() explicitly. Can I safely assume that the first statement in the function implicitly calls start()or restart() and will this work? Or is this undefined behavior?
    2. Why on earth did the original author of the code add that second statement? It just calls QTime::currentTime() but doesn't assign that time to any variable. Does QTime::currentTime() have any side-effects that I should be aware of here? I don't see anything mentioned at http://doc.qt.io/archives/qt-4.8/qtime.html#currentTime

    As for my question 1), the following test code seems to give me the correct elapsed time:

    #include <QDebug>
    #include <QTime>
    #include <chrono>
    #include <thread>
    
    int main()
    {
        QTime startTime = QTime::currentTime();
    
        std::this_thread::sleep_for(std::chrono::milliseconds(5000));
    
        qDebug() << startTime.elapsed();
    }
    

    Is this undefined behavior and am I just having pure luck? Or is it rock-solid waterproof?



  • @Bart_Vandewoestyne

    Reading the docs, QTime::start() only says: "Sets this time to the current time". So startTime.start() is only doing exactly the same as QTime startTime = QTime::currentTime();. And presumably startTime.elapsed(); is only doing same as QTime::currentTime() - startTime. Hence your code works.

    For the old code, it's only using startTime, which it assigns, so the stand-alone statement QTime::currentTime(); has no effect. You'd have to ask the author :), but I would presume it was unintended.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.