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:
- 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()
orrestart()
was called." Note however that we are not callingstart()
orrestart()
explicitly. Can I safely assume that the first statement in the function implicitly callsstart()
orrestart()
and will this work? Or is this undefined behavior? - 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. DoesQTime::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?
- 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
-
Reading the docs,
QTime::start()
only says: "Sets this time to the current time". SostartTime.start()
is only doing exactly the same asQTime startTime = QTime::currentTime();
. And presumablystartTime.elapsed();
is only doing same asQTime::currentTime() - startTime
. Hence your code works.For the old code, it's only using
startTime
, which it assigns, so the stand-alone statementQTime::currentTime();
has no effect. You'd have to ask the author :), but I would presume it was unintended.