![]() |
Qt 6.x
The Qt SDK
|
\inmodule QtCore More...
#include <qelapsedtimer.h>
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 |
Starts this timer. | |
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 this QElapsedTimer has already expired by timeout milliseconds (that is, more than timeout milliseconds have elapsed). | |
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. | |
\inmodule QtCore
The QElapsedTimer class provides a fast way to calculate elapsed times.
\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:
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:
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:
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.
using QElapsedTimer::Duration = std::chrono::nanoseconds |
Definition at line 26 of file qelapsedtimer.h.
using QElapsedTimer::TimePoint = std::chrono::time_point<std::chrono::steady_clock, Duration> |
Definition at line 27 of file qelapsedtimer.h.
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.
|
constexprdefault |
Constructs an invalid QElapsedTimer. A timer becomes valid once it has been started.
|
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.
Definition at line 179 of file qelapsedtimer.cpp.
References MonotonicClock.
|
noexcept |
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.
Definition at line 265 of file qelapsedtimer.cpp.
Referenced by elapsed(), and nsecsElapsed().
|
noexcept |
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.
Definition at line 338 of file qelapsedtimer.cpp.
References d1, d2, and other().
|
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.
Definition at line 299 of file qelapsedtimer.cpp.
References durationElapsed().
Referenced by QNetworkReplyHttpImplPrivate::_q_cacheLoadReadyRead(), QNetworkReplyImplPrivate::_q_copyReadyRead(), QQuickSpriteEngine::advance(), QNetworkReplyImplPrivate::appendDownstreamDataDownloadBuffer(), QNetworkReplyImplPrivate::appendDownstreamDataSignalEmissions(), QSocks5SocketEngine::close(), QQuickFlickablePrivate::computeCurrentTime(), QQuickPathViewPrivate::computeCurrentTime(), QQuickAnimatedNode::currentTime(), QUnifiedTimer::elapsed(), QSGDefaultAnimationDriver::elapsed(), QSGElapsedTimerAnimationDriver::elapsed(), QNetworkReplyHttpImplPrivate::emitReplyUploadProgress(), QNetworkReplyImplPrivate::emitUploadProgress(), QSGRhiAtlasTexture::Atlas::enqueueTextureUpload(), QComboBoxPrivateContainer::eventFilter(), QWindowSystemInterface::handleExtendedKeyEvent(), QWindowSystemInterface::handleTabletEnterLeaveProximityEvent(), QWindowSystemInterface::handleTabletEnterProximityEvent(), QWindowSystemInterface::handleTabletEvent(), QWindowSystemInterface::handleTabletEvent(), QWindowSystemInterface::handleTabletLeaveProximityEvent(), QWindowSystemInterface::handleWheelEvent(), QFutureInterfaceBasePrivate::internal_updateProgress(), QFutureInterfaceBasePrivate::internal_updateProgressValue(), QFutureInterfaceBase::isProgressUpdateNeeded(), main(), QScrollerPrivate::pushSegment(), QT_DEFINE_QPA_EVENT_HANDLER(), QT_DEFINE_QPA_EVENT_HANDLER(), QT_DEFINE_QPA_EVENT_HANDLER(), QT_DEFINE_QPA_EVENT_HANDLER(), QT_DEFINE_QPA_EVENT_HANDLER(), qt_handleKeyEvent(), QAlphaWidget::render(), QSGSoftwareRenderer::render(), QSGSoftwarePixmapRenderer::render(), QNetworkReplyHttpImplPrivate::replyDownloadData(), QNetworkReplyHttpImplPrivate::replyDownloadProgressSlot(), QSpringAnimation::restart(), QQuickStochasticEngine::restart(), QQuickSpriteEngine::restart(), QAlphaWidget::run(), QScrollerPrivate::setContentPositionHelperScrolling(), QWindowsCaRootFetcher::start(), QV4::ExecutionEngine::startTimer(), QBenchmarkTimeMeasurer::stop(), QUnifiedTimer::stopAnimationDriver(), QQuickVelocityCalculator::stopMeasuring(), QV4::ExecutionEngine::stopTimer(), QQuickShapePrivate::sync(), QSGSoftwareRenderThread::syncAndRender(), QSGRenderThread::syncAndRender(), QSGDistanceFieldGlyphCache::update(), QSpringAnimation::updateCurrentTime(), QQuickVelocityCalculator::velocity(), QAbstractSocket::waitForBytesWritten(), QSslSocket::waitForBytesWritten(), QSocks5SocketEnginePrivate::waitForConnected(), QAbstractSocket::waitForConnected(), QAbstractSocket::waitForDisconnected(), QSslSocket::waitForDisconnected(), QSslSocket::waitForEncrypted(), QHttpSocketEngine::waitForRead(), QSocks5SocketEngine::waitForRead(), QPacketProtocol::waitForReadyRead(), QAbstractSocket::waitForReadyRead(), QSslSocket::waitForReadyRead(), QHttpSocketEngine::waitForWrite(), and QSocks5SocketEngine::waitForWrite().
|
noexcept |
Returns true
if this QElapsedTimer has already expired by timeout milliseconds (that is, more than timeout milliseconds have elapsed).
The value of timeout can be -1 to indicate that this timer does not expire, in which case this function will always return false.
Definition at line 413 of file qelapsedtimer.cpp.
References elapsed().
Referenced by QQuickTextInputPrivate::hasPendingTripleClick().
|
noexcept |
Marks this QElapsedTimer object as invalid.
An invalid object can be checked with isValid(). Calculations of timer elapsed since invalid data are undefined and will likely produce bizarre results.
Definition at line 389 of file qelapsedtimer.cpp.
References invalidData.
Referenced by QAbstractItemViewPrivate::QAbstractItemViewPrivate(), QFutureInterfaceBasePrivate::QFutureInterfaceBasePrivate(), QNetworkReplyImplPrivate::_q_startOperation(), QQuickPathViewPrivate::handleMouseReleaseEvent(), QQuickPathViewPrivate::init(), QNetworkReplyHttpImplPrivate::postRequest(), QFutureInterfaceBase::reset(), QQuickVelocityCalculator::reset(), QWasmAudioSink::stop(), QWasmAudioSource::stop(), QAndroidCaptureSession::stop(), QQuickVelocityCalculator::stopMeasuring(), and QQuickTapHandler::wantsEventPoint().
|
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.
Definition at line 197 of file qelapsedtimer.cpp.
|
noexcept |
Returns false
if the timer has never been started or invalidated by a call to invalidate().
Definition at line 400 of file qelapsedtimer.cpp.
References invalidData.
Referenced by QQuickFlickablePrivate::computeCurrentTime(), QUnifiedTimer::elapsed(), QNetworkReplyHttpImplPrivate::emitReplyUploadProgress(), QNetworkReplyImplPrivate::emitUploadProgress(), QQuickPathViewPrivate::handleMouseMoveEvent(), QQuickPathViewPrivate::handleMouseReleaseEvent(), QFutureInterfaceBasePrivate::internal_updateProgress(), QFutureInterfaceBasePrivate::internal_updateProgressValue(), QFutureInterfaceBase::isProgressUpdateNeeded(), QV4::ExecutionEngine::startTimer(), QQuickVelocityCalculator::stopMeasuring(), and QQuickVelocityCalculator::velocity().
|
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.
Definition at line 320 of file qelapsedtimer.cpp.
|
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.
Definition at line 355 of file qelapsedtimer.cpp.
References other().
Referenced by restart().
|
noexcept |
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.
Definition at line 285 of file qelapsedtimer.cpp.
References durationElapsed().
Referenced by QCtfLibImpl::doTracepoint(), elapsedTestCaseSeconds(), QAudioSink::elapsedUSecs(), QAudioSource::elapsedUSecs(), main(), QQuickFrameAnimationPrivate::maybeTick(), QTestLog::nsecsFunctionTime(), QTestLog::nsecsTotalTime(), QSGRenderer::preprocess(), QSGRenderer::renderScene(), QSGOpenVGRenderLoop::renderWindow(), QSGGuiThreadRenderLoop::renderWindow(), QSGSoftwareRenderLoop::renderWindow(), QFFmpegSurfaceCaptureThread::run(), QDebugMessageServiceImpl::sendDebugMessage(), SimulationWorker::simulateFrame(), QQmlProfilerServiceImpl::startProfiling(), QSGRenderThread::syncAndRender(), QSGDistanceFieldGlyphCache::update(), QQuick3DParticleSystem::updateCurrentTime(), and QQuickFrameAnimationPrivate::updateState().
|
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:
Definition at line 244 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(), QJUnitTestLogger::enterTestData(), QTestLog::enterTestFunction(), QSGSoftwareRenderer::render(), QSGSoftwarePixmapRenderer::render(), 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().
|
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.
Definition at line 371 of file qelapsedtimer.cpp.
References other().
|
noexcept |
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:
Also, starting a timer makes it valid again.
Definition at line 214 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(), QSocks5SocketEngine::bind(), QSocks5SocketEngine::close(), QNetworkReplyHttpImplPrivate::emitReplyUploadProgress(), QNetworkReplyImplPrivate::emitUploadProgress(), QBackingStoreDefaultCompositor::flush(), QQuickPathViewPrivate::handleMousePressEvent(), QQuickFlickablePrivate::handlePressEvent(), QScrollerPrivate::init(), QProgressDialogPrivate::init(), QFutureInterfaceBasePrivate::internal_updateProgress(), QFutureInterfaceBasePrivate::internal_updateProgressValue(), main(), QQuickFlickablePrivate::maybeBeginDrag(), QNetworkReplyHttpImplPrivate::postRequest(), Q_TRACE_INSTRUMENT(), QFlickGestureRecognizer::recognize(), QSGSoftwareRenderer::render(), QSGSoftwarePixmapRenderer::render(), QSGRenderer::renderScene(), QSGOpenVGRenderLoop::renderWindow(), QSGGuiThreadRenderLoop::renderWindow(), QSGSoftwareRenderLoop::renderWindow(), restart(), QOpenGLCompositorBackingStore::rhiFlush(), QSGSoftwareRenderThread::run(), QSGRenderThread::run(), QFFmpegSurfaceCaptureThread::run(), QAlphaWidget::run(), QRollEffect::run(), QComboBox::showPopup(), SimulationWorker::simulateFrame(), QWindowsCaRootFetcher::start(), QAudioSource::start(), QBenchmarkTimeMeasurer::start(), QSGDefaultAnimationDriver::start(), QWasmAudioSink::start(), QWasmAudioSource::start(), QAudioSource::start(), QAndroidCaptureSession::start(), QTestLog::startLogging(), QJUnitTestLogger::startLogging(), QQuickVelocityCalculator::startMeasuring(), QV4::ExecutionEngine::startTimer(), QQuickShapePrivate::sync(), QSGSoftwareRenderThread::syncAndRender(), QSGRenderThread::syncAndRender(), QSGDistanceFieldGlyphCache::update(), QQuickStochasticEngine::updateSprites(), QQuickFrameAnimationPrivate::updateState(), QAbstractSocket::waitForBytesWritten(), QSslSocket::waitForBytesWritten(), QSocks5SocketEnginePrivate::waitForConnected(), QAbstractSocket::waitForConnected(), QAbstractSocket::waitForDisconnected(), QSslSocket::waitForDisconnected(), QSslSocket::waitForEncrypted(), QHttpSocketEngine::waitForRead(), QSocks5SocketEngine::waitForRead(), QPacketProtocol::waitForReadyRead(), QAbstractSocket::waitForReadyRead(), QSslSocket::waitForReadyRead(), QHttpSocketEngine::waitForWrite(), and QSocks5SocketEngine::waitForWrite().
|
friend |
Returns true
if lhs and rhs contain different times, false otherwise.
Definition at line 51 of file qelapsedtimer.h.
|
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 420 of file qelapsedtimer.cpp.
|
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 420 of file qelapsedtimer.cpp.
|
friend |
Returns true
if lhs and rhs contain the same time, false otherwise.
Definition at line 49 of file qelapsedtimer.h.