Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
QElapsedTimer Class Reference

\inmodule QtCore More...

#include <qelapsedtimer.h>

+ Collaboration diagram for QElapsedTimer:

Public Types

enum  ClockType {
  SystemTime , MonotonicClock , Q_DECL_ENUMERATOR_DEPRECATED_X , MachAbsoluteTime ,
  PerformanceCounter
}
 This enum contains the different clock types that QElapsedTimer may use. More...
 
using Duration = std::chrono::nanoseconds
 
using TimePoint = std::chrono::time_point<std::chrono::steady_clock, Duration>
 

Public Member Functions

constexpr QElapsedTimer ()=default
 
void start () noexcept
 \typealias QElapsedTimer::Duration Synonym for std::chrono::nanoseconds.
 
qint64 restart () noexcept
 Restarts the timer and returns the number of milliseconds elapsed since the previous start.
 
void invalidate () noexcept
 Marks this QElapsedTimer object as invalid.
 
bool isValid () const noexcept
 Returns false if the timer has never been started or invalidated by a call to invalidate().
 
Duration durationElapsed () const noexcept
 
qint64 nsecsElapsed () const noexcept
 
qint64 elapsed () const noexcept
 Returns the number of milliseconds since this QElapsedTimer was last started.
 
bool hasExpired (qint64 timeout) const noexcept
 Returns true if elapsed() exceeds the given timeout, otherwise false.
 
qint64 msecsSinceReference () const noexcept
 Returns the number of milliseconds between last time this QElapsedTimer object was started and its reference clock's start.
 
Duration durationTo (const QElapsedTimer &other) const noexcept
 
qint64 msecsTo (const QElapsedTimer &other) const noexcept
 Returns the number of milliseconds between this QElapsedTimer and other.
 
qint64 secsTo (const QElapsedTimer &other) const noexcept
 Returns the number of seconds between this QElapsedTimer and other.
 

Static Public Member Functions

static ClockType clockType () noexcept
 Returns the clock type that this QElapsedTimer implementation uses.
 
static bool isMonotonic () noexcept
 Returns true if this is a monotonic clock, false otherwise.
 

Friends

bool operator== (const QElapsedTimer &lhs, const QElapsedTimer &rhs) noexcept
 Returns true if lhs and rhs contain the same time, false otherwise.
 
bool operator!= (const QElapsedTimer &lhs, const QElapsedTimer &rhs) noexcept
 Returns true if lhs and rhs contain different times, false otherwise.
 
bool Q_CORE_EXPORT operator< (const QElapsedTimer &lhs, const QElapsedTimer &rhs) noexcept
 Returns true if lhs was started before rhs, false otherwise.
 

Related Symbols

(Note that these are not member symbols.)

bool operator< (const QElapsedTimer &lhs, const QElapsedTimer &rhs) noexcept
 Returns true if lhs was started before rhs, false otherwise.
 

Detailed Description

\inmodule QtCore

The QElapsedTimer class provides a fast way to calculate elapsed times.

Since
4.7

\reentrant

The QElapsedTimer class is usually used to quickly calculate how much time has elapsed between two events. Its API is similar to that of QTime, so code that was using that can be ported quickly to the new class.

However, unlike QTime, QElapsedTimer tries to use monotonic clocks if possible. This means it's not possible to convert QElapsedTimer objects to a human-readable time.

The typical use-case for the class is to determine how much time was spent in a slow operation. The simplest example of such a case is for debugging purposes, as in the following example:

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

In this example, the timer is started by a call to start() and the elapsed time is calculated by the elapsed() function.

The time elapsed can also be used to recalculate the time available for another operation, after the first one is complete. This is useful when the execution must complete within a certain time period, but several steps are needed. The \tt{waitFor}-type functions in QIODevice and its subclasses are good examples of such need. In that case, the code could be as follows:

{
int remainingTime = timeout - timer.elapsed();
if (remainingTime > 0)
slowOperation2(remainingTime);
}

Another use-case is to execute a certain operation for a specific timeslice. For this, QElapsedTimer provides the hasExpired() convenience function, which can be used to determine if a certain number of milliseconds has already elapsed:

{
while (!timer.hasExpired(ms))
}

It is often more convenient to use \l{QDeadlineTimer} in this case, which counts towards a timeout in the future instead of tracking elapsed time.

Definition at line 13 of file qelapsedtimer.h.

Member Typedef Documentation

◆ Duration

using QElapsedTimer::Duration = std::chrono::nanoseconds

Definition at line 26 of file qelapsedtimer.h.

◆ TimePoint

using QElapsedTimer::TimePoint = std::chrono::time_point<std::chrono::steady_clock, Duration>

Definition at line 27 of file qelapsedtimer.h.

Member Enumeration Documentation

◆ ClockType

This enum contains the different clock types that QElapsedTimer may use.

QElapsedTimer will always use the same clock type in a particular machine, so this value will not change during the lifetime of a program. It is provided so that QElapsedTimer can be used with other non-Qt implementations, to guarantee that the same reference clock is being used.

\value SystemTime The human-readable system time. This clock is not monotonic. \value MonotonicClock The system's monotonic clock, usually found in Unix systems. This clock is monotonic. \value TickCounter Not used anymore. \value MachAbsoluteTime The Mach kernel's absolute time (\macos and iOS). This clock is monotonic. \value PerformanceCounter The performance counter provided by Windows. This clock is monotonic.

Enumerator
SystemTime 
MonotonicClock 
Q_DECL_ENUMERATOR_DEPRECATED_X 
MachAbsoluteTime 
PerformanceCounter 

Definition at line 16 of file qelapsedtimer.h.

Constructor & Destructor Documentation

◆ QElapsedTimer()

QElapsedTimer::QElapsedTimer ( )
constexprdefault
Since
5.4

Constructs an invalid QElapsedTimer. A timer becomes valid once it has been started.

See also
isValid(), start()

Member Function Documentation

◆ clockType()

QElapsedTimer::ClockType QElapsedTimer::clockType ( )
staticnoexcept

Returns the clock type that this QElapsedTimer implementation uses.

Since Qt 6.6, QElapsedTimer uses {std::chrono::steady_clock}, so the clock type is always \l MonotonicClock.

See also
isMonotonic()

Definition at line 179 of file qelapsedtimer.cpp.

References MonotonicClock.

◆ durationElapsed()

auto QElapsedTimer::durationElapsed ( ) const
noexcept
Since
6.6

Returns a {std::chrono::nanoseconds} with the time since this QElapsedTimer was last started.

Calling this function on a QElapsedTimer that is invalid results in undefined behavior.

On platforms that do not provide nanosecond resolution, the value returned will be the best estimate available.

See also
start(), restart(), hasExpired(), invalidate()

Definition at line 275 of file qelapsedtimer.cpp.

Referenced by elapsed(), and nsecsElapsed().

+ Here is the caller graph for this function:

◆ durationTo()

auto QElapsedTimer::durationTo ( const QElapsedTimer & other) const
noexcept
Since
6.6

Returns the time difference between this QElapsedTimer and other as a {std::chrono::nanoseconds}. If other was started before this object, the returned value will be negative. If it was started later, the returned value will be positive.

The return value is undefined if this object or other were invalidated.

See also
secsTo(), elapsed()

Definition at line 348 of file qelapsedtimer.cpp.

References d1, d2, and other().

+ Here is the call graph for this function:

◆ elapsed()

qint64 QElapsedTimer::elapsed ( ) const
noexcept

Returns the number of milliseconds since this QElapsedTimer was last started.

Calling this function on a QElapsedTimer that is invalid results in undefined behavior.

See also
start(), restart(), hasExpired(), isValid(), invalidate()

Definition at line 309 of file qelapsedtimer.cpp.

References durationElapsed().

Referenced by QNetworkReplyHttpImplPrivate::_q_cacheLoadReadyRead(), QNetworkReplyImplPrivate::_q_copyReadyRead(), QQuickSpriteEngine::advance(), QNetworkReplyImplPrivate::appendDownstreamDataDownloadBuffer(), QNetworkReplyImplPrivate::appendDownstreamDataSignalEmissions(), QQuickFlickablePrivate::computeCurrentTime(), QQuickPathViewPrivate::computeCurrentTime(), QQuickAnimatedNode::currentTime(), QUnifiedTimer::elapsed(), QSGDefaultAnimationDriver::elapsed(), QSGElapsedTimerAnimationDriver::elapsed(), QNetworkReplyHttpImplPrivate::emitReplyUploadProgress(), QNetworkReplyImplPrivate::emitUploadProgress(), QComboBoxPrivateContainer::eventFilter(), QFutureInterfaceBasePrivate::internal_updateProgress(), QFutureInterfaceBasePrivate::internal_updateProgressValue(), QFutureInterfaceBase::isProgressUpdateNeeded(), main(), QScrollerPrivate::pushSegment(), QAlphaWidget::render(), QNetworkReplyHttpImplPrivate::replyDownloadData(), QNetworkReplyHttpImplPrivate::replyDownloadProgressSlot(), QSpringAnimation::restart(), QQuickStochasticEngine::restart(), QQuickSpriteEngine::restart(), QAlphaWidget::run(), QScrollerPrivate::setContentPositionHelperScrolling(), QV4::ExecutionEngine::startTimer(), QBenchmarkTimeMeasurer::stop(), QUnifiedTimer::stopAnimationDriver(), QQuickVelocityCalculator::stopMeasuring(), QV4::ExecutionEngine::stopTimer(), QQuickShapePrivate::sync(), QSGSoftwareRenderThread::syncAndRender(), QSpringAnimation::updateCurrentTime(), and QQuickVelocityCalculator::velocity().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ hasExpired()

bool QElapsedTimer::hasExpired ( qint64 timeout) const
noexcept

Returns true if elapsed() exceeds the given timeout, otherwise false.

A negative timeout is interpreted as infinite, so false is returned in this case. Otherwise, this is equivalent to {elapsed() > timeout}. You can do the same for a duration by comparing durationElapsed() to a duration timeout.

See also
elapsed(), QDeadlineTimer

Definition at line 425 of file qelapsedtimer.cpp.

References elapsed().

Referenced by QQuickTextInputPrivate::hasPendingTripleClick(), and QtWaylandClient::QWaylandWindow::timerEvent().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ invalidate()

void QElapsedTimer::invalidate ( )
noexcept

◆ isMonotonic()

bool QElapsedTimer::isMonotonic ( )
staticnoexcept

Returns true if this is a monotonic clock, false otherwise.

See the information on the different clock types to understand which ones are monotonic.

Since Qt 6.6, QElapsedTimer uses {std::chrono::steady_clock}, so this function now always returns true.

See also
clockType(), QElapsedTimer::ClockType

Definition at line 197 of file qelapsedtimer.cpp.

◆ isValid()

◆ msecsSinceReference()

qint64 QElapsedTimer::msecsSinceReference ( ) const
noexcept

Returns the number of milliseconds between last time this QElapsedTimer object was started and its reference clock's start.

This number is usually arbitrary for all clocks except the QElapsedTimer::SystemTime clock. For that clock type, this number is the number of milliseconds since January 1st, 1970 at 0:00 UTC (that is, it is the Unix time expressed in milliseconds).

On Linux, Windows and Apple platforms, this value is usually the time since the system boot, though it usually does not include the time the system has spent in sleep states.

See also
clockType(), elapsed()

Definition at line 330 of file qelapsedtimer.cpp.

◆ msecsTo()

qint64 QElapsedTimer::msecsTo ( const QElapsedTimer & other) const
noexcept

Returns the number of milliseconds between this QElapsedTimer and other.

If other was started before this object, the returned value will be negative. If it was started later, the returned value will be positive.

The return value is undefined if this object or other were invalidated.

See also
secsTo(), elapsed()

Definition at line 365 of file qelapsedtimer.cpp.

References other().

Referenced by restart().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ nsecsElapsed()

qint64 QElapsedTimer::nsecsElapsed ( ) const
noexcept
Since
4.8

Returns the number of nanoseconds since this QElapsedTimer was last started.

Calling this function on a QElapsedTimer that is invalid results in undefined behavior.

On platforms that do not provide nanosecond resolution, the value returned will be the best estimate available.

See also
start(), restart(), hasExpired(), invalidate()

Definition at line 295 of file qelapsedtimer.cpp.

References durationElapsed().

Referenced by QCtfLibImpl::doTracepoint(), QAudioSink::elapsedUSecs(), QAudioSource::elapsedUSecs(), main(), QQuickFrameAnimationPrivate::maybeTick(), QDebugMessageServiceImpl::sendDebugMessage(), SimulationWorker::simulateFrame(), QQmlProfilerServiceImpl::startProfiling(), QCtfLibImpl::tracepointEnabled(), QQuick3DParticleSystem::updateCurrentTime(), and QQuickFrameAnimationPrivate::updateState().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ restart()

qint64 QElapsedTimer::restart ( )
noexcept

Restarts the timer and returns the number of milliseconds elapsed since the previous start.

This function is equivalent to obtaining the elapsed time with elapsed() and then starting the timer again with start(), but it does so in one single operation, avoiding the need to obtain the clock value twice.

Calling this function on a QElapsedTimer that is invalid results in undefined behavior.

The following example illustrates how to use this function to calibrate a parameter to a slow operation (for example, an iteration count) so that this operation takes at least 250 milliseconds:

int count = 1;
do {
count *= 2;
} while (timer.restart() < 250);
return count;
See also
start(), invalidate(), elapsed(), isValid()

Definition at line 254 of file qelapsedtimer.cpp.

References msecsTo(), and start().

Referenced by QNetworkReplyHttpImplPrivate::_q_cacheLoadReadyRead(), QNetworkReplyImplPrivate::_q_copyReadyRead(), QSGDefaultAnimationDriver::advance(), QNetworkReplyImplPrivate::appendDownstreamDataDownloadBuffer(), QNetworkReplyImplPrivate::appendDownstreamDataSignalEmissions(), QNetworkReplyHttpImplPrivate::emitReplyUploadProgress(), QNetworkReplyImplPrivate::emitUploadProgress(), QNetworkReplyHttpImplPrivate::replyDownloadData(), QNetworkReplyHttpImplPrivate::replyDownloadProgressSlot(), QQuickAnimatedNode::setCurrentTime(), SimulationWorker::simulateFrame(), QAudioSink::start(), QSGDefaultAnimationDriver::start(), QSGElapsedTimerAnimationDriver::start(), QQuickAnimatedNode::start(), QAudioSink::start(), QSGSoftwareRenderThread::syncAndRender(), QSGRenderThread::syncAndRender(), and QQuick3DParticleSystem::updateCurrentTime().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ secsTo()

qint64 QElapsedTimer::secsTo ( const QElapsedTimer & other) const
noexcept

Returns the number of seconds between this QElapsedTimer and other.

If other was started before this object, the returned value will be negative. If it was started later, the returned value will be positive.

Calling this function on or with a QElapsedTimer that is invalid results in undefined behavior.

See also
msecsTo(), elapsed()

Definition at line 381 of file qelapsedtimer.cpp.

References other().

+ Here is the call graph for this function:

◆ start()

void QElapsedTimer::start ( )
noexcept

\typealias QElapsedTimer::Duration Synonym for std::chrono::nanoseconds.

\typealias QElapsedTimer::TimePoint Synonym for {std::chrono::time_point<std::chrono::steady_clock, Duration>}.

Starts this timer. Once started, a timer value can be checked with elapsed() or msecsSinceReference().

Normally, a timer is started just before a lengthy operation, such as:

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

Also, starting a timer makes it valid again.

See also
restart(), invalidate(), elapsed()

Definition at line 224 of file qelapsedtimer.cpp.

References now, and QT6_ONLY().

Referenced by QCtfLibImpl::QCtfLibImpl(), QDebugMessageServiceImpl::QDebugMessageServiceImpl(), QMessagePattern::QMessagePattern(), QQuick3DRenderStats::QQuick3DRenderStats(), QQuickSpringAnimationPrivate::QQuickSpringAnimationPrivate(), QWaylandCompositorPrivate::QWaylandCompositorPrivate(), QNetworkReplyImplPrivate::_q_startOperation(), QSocks5BindStore::add(), QSvgNode::draw(), QNetworkReplyHttpImplPrivate::emitReplyUploadProgress(), QNetworkReplyImplPrivate::emitUploadProgress(), QSqlQuery::exec(), QSqlQuery::exec(), QQuickPathViewPrivate::handleMousePressEvent(), QQuickFlickablePrivate::handlePressEvent(), QtWaylandClient::QWaylandWindow::handleUpdate(), QScrollerPrivate::init(), QProgressDialogPrivate::init(), QFutureInterfaceBasePrivate::internal_updateProgress(), QFutureInterfaceBasePrivate::internal_updateProgressValue(), main(), QQuickFlickablePrivate::maybeBeginDrag(), QNetworkReplyHttpImplPrivate::postRequest(), QHostInfoCache::put(), QSGOpenVGRenderLoop::renderWindow(), QSGGuiThreadRenderLoop::renderWindow(), QSGSoftwareRenderLoop::renderWindow(), restart(), QSGSoftwareRenderThread::run(), QSGRenderThread::run(), QAlphaWidget::run(), QRollEffect::run(), QV4::MemoryManager::runGC(), QComboBox::showPopup(), SimulationWorker::simulateFrame(), QWindowsCaRootFetcher::start(), QAudioSource::start(), QBenchmarkTimeMeasurer::start(), QSGDefaultAnimationDriver::start(), QWasmAudioSink::start(), QWasmAudioSource::start(), QAudioSource::start(), QAndroidCaptureSession::start(), QQuickVelocityCalculator::startMeasuring(), QV4::ExecutionEngine::startTimer(), QQuickShapePrivate::sync(), QSGSoftwareRenderThread::syncAndRender(), QSGRenderThread::syncAndRender(), QQuickStochasticEngine::updateSprites(), QQuickFrameAnimationPrivate::updateState(), QSslSocket::waitForBytesWritten(), QSslSocket::waitForDisconnected(), QSslSocket::waitForEncrypted(), QPacketProtocol::waitForReadyRead(), and QSslSocket::waitForReadyRead().

+ Here is the call graph for this function:

Friends And Related Symbol Documentation

◆ operator!=

bool QElapsedTimer::operator!= ( const QElapsedTimer & lhs,
const QElapsedTimer & rhs )
friend

Returns true if lhs and rhs contain different times, false otherwise.

Definition at line 51 of file qelapsedtimer.h.

◆ operator<() [1/2]

bool operator< ( const QElapsedTimer & lhs,
const QElapsedTimer & rhs )
related

Returns true if lhs was started before rhs, false otherwise.

The returned value is undefined if one of the two parameters is invalid and the other isn't. However, two invalid timers are equal and thus this function will return false.

Definition at line 432 of file qelapsedtimer.cpp.

◆ operator< [2/2]

bool operator< ( const QElapsedTimer & lhs,
const QElapsedTimer & rhs )
friend

Returns true if lhs was started before rhs, false otherwise.

The returned value is undefined if one of the two parameters is invalid and the other isn't. However, two invalid timers are equal and thus this function will return false.

Definition at line 432 of file qelapsedtimer.cpp.

◆ operator==

bool QElapsedTimer::operator== ( const QElapsedTimer & lhs,
const QElapsedTimer & rhs )
friend

Returns true if lhs and rhs contain the same time, false otherwise.

Definition at line 49 of file qelapsedtimer.h.


The documentation for this class was generated from the following files: