Qt 4.8
Public Types | Public Functions | Static Public Functions | Properties | Friends | List of all members
QElapsedTimer Class Reference

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

#include <qelapsedtimer.h>

Public Types

enum  ClockType {
  SystemTime, MonotonicClock, TickCounter, MachAbsoluteTime,
  PerformanceCounter
}
 This enum contains the different clock types that QElapsedTimer may use. More...
 

Public Functions

qint64 elapsed () const
 Returns the number of milliseconds since this QElapsedTimer was last started. More...
 
bool hasExpired (qint64 timeout) const
 Returns true if this QElapsedTimer has already expired by timeout milliseconds (that is, more than timeout milliseconds have elapsed). More...
 
void invalidate ()
 Marks this QElapsedTimer object as invalid. More...
 
bool isValid () const
 Returns false if this object was invalidated by a call to invalidate() and has not been restarted since. More...
 
qint64 msecsSinceReference () const
 Returns the number of milliseconds between last time this QElapsedTimer object was started and its reference clock's start. More...
 
qint64 msecsTo (const QElapsedTimer &other) const
 Returns the number of milliseconds between this QElapsedTimer and other. More...
 
qint64 nsecsElapsed () const
 Returns the number of nanoseconds since this QElapsedTimer was last started. More...
 
bool operator!= (const QElapsedTimer &other) const
 Returns true if this object and other contain different times. More...
 
bool operator== (const QElapsedTimer &other) const
 Returns true if this object and other contain the same time. More...
 
qint64 restart ()
 Restarts the timer and returns the time elapsed since the previous start. More...
 
qint64 secsTo (const QElapsedTimer &other) const
 Returns the number of seconds between this QElapsedTimer and other. More...
 
void start ()
 Starts this timer. More...
 

Static Public Functions

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

Properties

qint64 t1
 
qint64 t2
 

Friends

bool Q_CORE_EXPORT operator< (const QElapsedTimer &v1, const QElapsedTimer &v2)
 Returns true if v1 was started before v2, false otherwise. More...
 

Detailed Description

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

Since
4.7
Note
This class or function is reentrant.
Attention
Module: QtCore

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:

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

In this example, the timer is started by a call to start() and the elapsed timer 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 waitFor-type functions in QIODevice and its subclasses are good examples of such need. In that case, the code could be as follows:

void executeSlowOperations(int timeout)
{
timer.start();
slowOperation1();
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:

void executeOperationsForTime(int ms)
{
timer.start();
while (!timer.hasExpired(ms))
slowOperation1();
}

Reference clocks

QElapsedTimer will use the platform's monotonic reference clock in all platforms that support it (see QElapsedTimer::isMonotonic()). This has the added benefit that QElapsedTimer is immune to time adjustments, such as the user correcting the time. Also unlike QTime, QElapsedTimer is immune to changes in the timezone settings, such as daylight savings periods.

On the other hand, this means QElapsedTimer values can only be compared with other values that use the same reference. This is especially true if the time since the reference is extracted from the QElapsedTimer object (QElapsedTimer::msecsSinceReference()) and serialised. These values should never be exchanged across the network or saved to disk, since there's no telling whether the computer node receiving the data is the same as the one originating it or if it has rebooted since.

It is, however, possible to exchange the value with other processes running on the same machine, provided that they also use the same reference clock. QElapsedTimer will always use the same clock, so it's safe to compare with the value coming from another process in the same machine. If comparing to values produced by other APIs, you should check that the clock used is the same as QElapsedTimer (see QElapsedTimer::clockType()).

Definition at line 53 of file qelapsedtimer.h.

Enumerations

◆ 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.

  • SystemTime The human-readable system time. This clock is not monotonic.
  • MonotonicClock The system's monotonic clock, usually found in Unix systems. This clock is monotonic and does not overflow.
  • TickCounter The system's tick counter, used on Windows and Symbian systems. This clock may overflow.
  • MachAbsoluteTime The Mach kernel's absolute time (Mac OS X). This clock is monotonic and does not overflow.
  • PerformanceCounter The high-resolution performance counter provided by Windows. This clock is monotonic and does not overflow.

SystemTime

The system time clock is purely the real time, expressed in milliseconds since Jan 1, 1970 at 0:00 UTC. It's equivalent to the value returned by the C and POSIX time function, with the milliseconds added. This clock type is currently only used on Unix systems that do not support monotonic clocks (see below).

This is the only non-monotonic clock that QElapsedTimer may use.

MonotonicClock

This is the system's monotonic clock, expressed in milliseconds since an arbitrary point in the past. This clock type is used on Unix systems which support POSIX monotonic clocks (_POSIX_MONOTONIC_CLOCK).

This clock does not overflow.

TickCounter

The tick counter clock type is based on the system's or the processor's tick counter, multiplied by the duration of a tick. This clock type is used on Windows and Symbian platforms. If the high-precision performance counter is available on Windows, the PerformanceCounter clock type is used instead.

The TickCounter clock type is the only clock type that may overflow. Windows Vista and Windows Server 2008 support the extended 64-bit tick counter, which allows avoiding the overflow.

On Windows systems, the clock overflows after 2^32 milliseconds, which corresponds to roughly 49.7 days. This means two processes's reckoning of the time since the reference may be different by multiples of 2^32 milliseconds. When comparing such values, it's recommended that the high 32 bits of the millisecond count be masked off.

On Symbian systems, the overflow happens after 2^32 ticks, the duration of which can be obtained from the platform HAL using the constant HAL::ENanoTickPeriod. When comparing values between processes, it's necessary to divide the value by the tick duration and mask off the high 32 bits.

MachAbsoluteTime

This clock type is based on the absolute time presented by Mach kernels, such as that found on Mac OS X. This clock type is presented separately from MonotonicClock since Mac OS X is also a Unix system and may support a POSIX monotonic clock with values differing from the Mach absolute time.

This clock is monotonic and does not overflow.

PerformanceCounter

This clock uses the Windows functions QueryPerformanceCounter and QueryPerformanceFrequency to access the system's high-precision performance counter. Since this counter may not be available on all systems, QElapsedTimer will fall back to the TickCounter clock automatically, if this clock cannot be used.

This clock is monotonic and does not overflow.

See also
clockType(), isMonotonic()
Enumerator
SystemTime 
MonotonicClock 
TickCounter 
MachAbsoluteTime 
PerformanceCounter 

Definition at line 56 of file qelapsedtimer.h.

Functions

◆ clockType()

QElapsedTimer::ClockType QElapsedTimer::clockType ( )
static

Returns the clock type that this QElapsedTimer implementation uses.

See also
isMonotonic()

Definition at line 52 of file qelapsedtimer_generic.cpp.

Referenced by fractionAdjustment(), and getTickCount().

53 {
54  return SystemTime;
55 }

◆ elapsed()

qint64 QElapsedTimer::elapsed ( ) const

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

Calling this function in a QElapsedTimer that was invalidated will result in undefined results.

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

Definition at line 132 of file qelapsedtimer_generic.cpp.

Referenced by QSocks5SocketEngine::bind(), QBenchmarkTimeMeasurer::checkpoint(), QSocks5SocketEngine::close(), QAudioInputPrivate::deviceReady(), QAudioOutputPrivate::deviceReady(), QDeclarativeItemPrivate::elapsed(), elapsedAndRestart(), QAudioInputPrivate::elapsedUSecs(), QAudioOutputPrivate::elapsedUSecs(), QX11EmbedContainer::embedClient(), QWorkspace::eventFilter(), QAudioInputPrivate::feedback(), QAudioOutputPrivate::freeBlocks(), QJSDebuggerAgent::functionEntry(), QJSDebuggerAgent::functionExit(), QHostInfoCache::get(), getTickCount(), hasExpired(), initializeDb(), QFutureInterfaceBasePrivate::internal_updateProgress(), QFutureInterfaceBase::isProgressUpdateNeeded(), load(), QScrollBar::mousePressEvent(), QWorkspaceTitleBar::mousePressEvent(), nsecsElapsed(), QJSDebuggerAgent::positionChange(), QEventLoop::processEvents(), QCoreApplication::processEvents(), qt_gettime(), qt_x11_wait_for_window_manager(), QTest::qWait(), QAlphaWidget::render(), QAlphaWidget::run(), QJSDebuggerAgent::scriptLoad(), QRollEffect::scroll(), QBenchmarkTimeMeasurer::stop(), QSslSocketPrivate::systemCaCertificates(), QSemaphore::tryAcquire(), QUnifiedTimer::updateAnimationsTime(), QSslSocket::waitForBytesWritten(), QProcess::waitForBytesWritten(), QAbstractSocket::waitForBytesWritten(), QProcessPrivate::waitForBytesWritten(), QXlibScreen::waitForClipboardEvent(), QAbstractSocket::waitForConnected(), QSocks5SocketEnginePrivate::waitForConnected(), QSslSocket::waitForDisconnected(), QAbstractSocket::waitForDisconnected(), QThreadPoolPrivate::waitForDone(), QSslSocket::waitForEncrypted(), QProcess::waitForFinished(), QProcessPrivate::waitForFinished(), QSocks5SocketEngine::waitForRead(), QHttpSocketEngine::waitForRead(), QPacketProtocol::waitForReadyRead(), QSslSocket::waitForReadyRead(), QAbstractSocket::waitForReadyRead(), QProcessPrivate::waitForReadyRead(), QSocks5SocketEngine::waitForWrite(), and QHttpSocketEngine::waitForWrite().

133 {
135 }
static qint64 currentMSecsSinceEpoch()
Returns the number of milliseconds since 1970-01-01T00:00:00 Universal Coordinated Time...
Definition: qdatetime.cpp:3162

◆ hasExpired()

bool QElapsedTimer::hasExpired ( qint64  timeout) const

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.

See also
elapsed()

Definition at line 269 of file qelapsedtimer.cpp.

Referenced by QX11Data::dndEnable().

270 {
271  // if timeout is -1, quint64(timeout) is LLINT_MAX, so this will be
272  // considered as never expired
273  return quint64(elapsed()) > quint64(timeout);
274 }
qint64 elapsed() const
Returns the number of milliseconds since this QElapsedTimer was last started.
unsigned __int64 quint64
Definition: qglobal.h:943

◆ invalidate()

void QElapsedTimer::invalidate ( )

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.

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

Definition at line 245 of file qelapsedtimer.cpp.

Referenced by QDeclarativeFlickablePrivate::init(), QAbstractItemViewPrivate::QAbstractItemViewPrivate(), QFutureInterfaceBasePrivate::QFutureInterfaceBasePrivate(), QUnifiedTimer::QUnifiedTimer(), QSwipeGestureRecognizer::reset(), and QUnifiedTimer::timerEvent().

246 {
247  t1 = t2 = invalidData;
248 }
static const qint64 invalidData

◆ isMonotonic()

bool QElapsedTimer::isMonotonic ( )
static

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

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

See also
clockType(), QElapsedTimer::ClockType

Definition at line 64 of file qelapsedtimer_generic.cpp.

Referenced by fractionAdjustment(), getTickCount(), QEventDispatcherQPAPrivate::hasIntegration(), QTimerInfoList::QTimerInfoList(), QEventDispatcherBlackberry::select(), and QTimerInfoList::updateCurrentTime().

65 {
66  return false;
67 }

◆ isValid()

bool QElapsedTimer::isValid ( ) const

Returns false if this object was invalidated by a call to invalidate() and has not been restarted since.

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

Definition at line 256 of file qelapsedtimer.cpp.

Referenced by QFutureInterfaceBasePrivate::internal_updateProgress(), QFutureInterfaceBase::isProgressUpdateNeeded(), and QUnifiedTimer::timerEvent().

257 {
258  return t1 != invalidData && t2 != invalidData;
259 }
static const qint64 invalidData

◆ msecsSinceReference()

qint64 QElapsedTimer::msecsSinceReference ( ) const

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).

See also
clockType(), elapsed()

Definition at line 148 of file qelapsedtimer_generic.cpp.

Referenced by elapsedAndRestart(), getTickCount(), qt_gettime(), and QTest::seedRandom().

149 {
150  return t1;
151 }

◆ msecsTo()

qint64 QElapsedTimer::msecsTo ( const QElapsedTimer other) const

Returns the number of milliseconds between this QElapsedTimer and other.

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

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

See also
secsTo(), elapsed()

Definition at line 163 of file qelapsedtimer_generic.cpp.

Referenced by QX11Data::clipboardWaitForEvent(), elapsedAndRestart(), QFileInfoGatherer::fetch(), getTickCount(), qt_gettime(), and secsTo().

164 {
165  qint64 diff = other.t1 - t1;
166  return diff;
167 }
static Bigint * diff(Bigint *a, Bigint *b)
__int64 qint64
Definition: qglobal.h:942

◆ nsecsElapsed()

qint64 QElapsedTimer::nsecsElapsed ( ) const

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

Since
4.8

Calling this function in a QElapsedTimer that was invalidated will result in undefined results.

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 120 of file qelapsedtimer_generic.cpp.

Referenced by QDeclarativeDebugTrace::addEventImpl(), elapsedAndRestart(), QDeclarativeDebugTrace::endRangeImpl(), getTickCount(), QMutex::lockInternal(), qt_gettime(), QDeclarativeDebugTrace::rangeDataImpl(), QDeclarativeDebugTrace::rangeLocationImpl(), QDeclarativeDebugTrace::startRangeImpl(), and QMutexPrivate::wait().

121 {
122  return elapsed() * 1000000;
123 }
qint64 elapsed() const
Returns the number of milliseconds since this QElapsedTimer was last started.

◆ operator!=()

bool QElapsedTimer::operator!= ( const QElapsedTimer other) const
inline

Returns true if this object and other contain different times.

Definition at line 81 of file qelapsedtimer.h.

82  { return !(*this == other); }

◆ operator==()

bool QElapsedTimer::operator== ( const QElapsedTimer other) const
inline

Returns true if this object and other contain the same time.

Definition at line 79 of file qelapsedtimer.h.

80  { return t1 == other.t1 && t2 == other.t2; }

◆ restart()

qint64 QElapsedTimer::restart ( )

Restarts the timer and returns the time 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.

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;
timer.start();
do {
count *= 2;
slowOperation2(count);
} while (timer.restart() < 250);
return count;
See also
start(), invalidate(), elapsed()

Definition at line 98 of file qelapsedtimer_generic.cpp.

Referenced by QAudioInputPrivate::deviceReady(), QAudioOutputPrivate::deviceReady(), elapsedAndRestart(), QAudioInputPrivate::feedback(), QAudioOutputPrivate::freeBlocks(), QAudioInputPrivate::freeBlocks(), QJSDebuggerAgent::functionEntry(), getTickCount(), QAudioInputPrivate::open(), QAudioOutputPrivate::open(), qt_gettime(), QSwipeGestureRecognizer::recognize(), QDeclarativeItemPrivate::restart(), and start().

99 {
100  qint64 old = t1;
102  t2 = 0;
103  return t1 - old;
104 }
static qint64 currentMSecsSinceEpoch()
Returns the number of milliseconds since 1970-01-01T00:00:00 Universal Coordinated Time...
Definition: qdatetime.cpp:3162
__int64 qint64
Definition: qglobal.h:942

◆ secsTo()

qint64 QElapsedTimer::secsTo ( const QElapsedTimer other) const

Returns the number of seconds between this QElapsedTimer and other.

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

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

See also
msecsTo(), elapsed()

Definition at line 178 of file qelapsedtimer_generic.cpp.

Referenced by elapsedAndRestart(), getTickCount(), and qt_gettime().

179 {
180  return msecsTo(other) / 1000;
181 }
qint64 msecsTo(const QElapsedTimer &other) const
Returns the number of milliseconds between this QElapsedTimer and other.

◆ start()

void QElapsedTimer::start ( )

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:

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

Also, starting a timer makes it valid again.

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

Definition at line 79 of file qelapsedtimer_generic.cpp.

Referenced by QSocks5BindStore::add(), QSocks5SocketEngine::bind(), QX11Data::clipboardWaitForEvent(), QSocks5SocketEngine::close(), QX11Data::dndEnable(), elapsedAndRestart(), QX11EmbedContainer::embedClient(), QWorkspace::eventFilter(), QFileInfoGatherer::fetch(), QFileInfoGatherer::getFileInfos(), getTickCount(), initializeDb(), QFutureInterfaceBasePrivate::internal_updateProgress(), load(), QMutex::lockInternal(), QScrollBar::mousePressEvent(), QWorkspaceTitleBar::mousePressEvent(), QEventLoop::processEvents(), QCoreApplication::processEvents(), QHostInfoCache::put(), QDeclarativeDebugTrace::QDeclarativeDebugTrace(), QJSDebugService::QJSDebugService(), qt_gettime(), qt_x11_wait_for_window_manager(), QTest::qWait(), QWindowsStylePrivate::QWindowsStylePrivate(), QSwipeGestureRecognizer::recognize(), QAlphaWidget::run(), QRollEffect::run(), QTest::seedRandom(), QBenchmarkTimeMeasurer::start(), QDeclarativeItemPrivate::start(), QSslSocketPrivate::systemCaCertificates(), QUnifiedTimer::timerEvent(), QSemaphore::tryAcquire(), QMutexPrivate::wait(), QSslSocket::waitForBytesWritten(), QProcess::waitForBytesWritten(), QAbstractSocket::waitForBytesWritten(), QProcessPrivate::waitForBytesWritten(), QXlibScreen::waitForClipboardEvent(), QAbstractSocket::waitForConnected(), QSocks5SocketEnginePrivate::waitForConnected(), QSslSocket::waitForDisconnected(), QAbstractSocket::waitForDisconnected(), QThreadPoolPrivate::waitForDone(), QSslSocket::waitForEncrypted(), QProcess::waitForFinished(), QProcessPrivate::waitForFinished(), QSocks5SocketEngine::waitForRead(), QHttpSocketEngine::waitForRead(), QPacketProtocol::waitForReadyRead(), QSslSocket::waitForReadyRead(), QAbstractSocket::waitForReadyRead(), QProcessPrivate::waitForReadyRead(), QSocks5SocketEngine::waitForWrite(), and QHttpSocketEngine::waitForWrite().

80 {
81  restart();
82 }
qint64 restart()
Restarts the timer and returns the time elapsed since the previous start.

Friends and Related Functions

◆ operator<

bool operator< ( const QElapsedTimer v1,
const QElapsedTimer v2 
)
friend

Returns true if v1 was started before v2, 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 127 of file qelapsedtimer_mac.cpp.

Referenced by secsTo().

128 {
129  return v1.t1 < v2.t1;
130 }

Properties

◆ t1

qint64 QElapsedTimer::t1
private

◆ t2

qint64 QElapsedTimer::t2
private

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