QElapsedTimer¶

PyQt5.QtCore.QElapsedTimer

Description¶

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

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:

# This code needs porting to Python.

# /****************************************************************************
# **
# ** Copyright (C) 2016 The Qt Company Ltd.
# ** Contact: https://www.qt.io/licensing/
# **
# ** This file is part of the QtNetwork module of the Qt Toolkit.
# **
# ** $QT_BEGIN_LICENSE:BSD$
# ** Commercial License Usage
# ** Licensees holding valid commercial Qt licenses may use this file in
# ** accordance with the commercial license agreement provided with the
# ** Software or, alternatively, in accordance with the terms contained in
# ** a written agreement between you and The Qt Company. For licensing terms
# ** and conditions see https://www.qt.io/terms-conditions. For further
# ** information use the contact form at https://www.qt.io/contact-us.
# **
# ** BSD License Usage
# ** Alternatively, you may use this file under the terms of the BSD license
# ** as follows:
# **
# ** "Redistribution and use in source and binary forms, with or without
# ** modification, are permitted provided that the following conditions are
# ** met:
# **   * Redistributions of source code must retain the above copyright
# **     notice, this list of conditions and the following disclaimer.
# **   * Redistributions in binary form must reproduce the above copyright
# **     notice, this list of conditions and the following disclaimer in
# **     the documentation and/or other materials provided with the
# **     distribution.
# **   * Neither the name of The Qt Company Ltd nor the names of its
# **     contributors may be used to endorse or promote products derived
# **     from this software without specific prior written permission.
# **
# **
# ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
# **
# ** $QT_END_LICENSE$
# **
# ****************************************************************************/
# #include <QtCore>

# void slowOperation1()
# {
#     static char buf[256];
#     for (int i = 0; i < (1<<20); ++i)
#         buf[i % sizeof buf] = i;
# }

# void slowOperation2(int) { slowOperation1(); }

# void startExample()
# {
# //![0]
#     QElapsedTimer timer;
#     timer.start();

#     slowOperation1();

#     qDebug() << "The slow operation took" << timer.elapsed() << "milliseconds";
# //![0]
# }

# //![1]
# void executeSlowOperations(int timeout)
# {
#     QElapsedTimer timer;
#     timer.start();
#     slowOperation1();

#     int remainingTime = timeout - timer.elapsed();
#     if (remainingTime > 0)
#         slowOperation2(remainingTime);
# }
# //![1]

# //![2]
# void executeOperationsForTime(int ms)
# {
#     QElapsedTimer timer;
#     timer.start();

#     while (!timer.hasExpired(ms))
#         slowOperation1();
# }
# //![2]

# int restartExample()
# {
# //![3]
#     QElapsedTimer timer;

#     int count = 1;
#     timer.start();
#     do {
#         count *= 2;
#         slowOperation2(count);
#     } while (timer.restart() < 250);

#     return count;
# //![3]
# }

# int main(int argc, char **argv)
# {
#     QCoreApplication app(argc, argv);

#     startExample();
#     restartExample();
#     executeSlowOperations(5);
#     executeOperationsForTime(5);
# }

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:

# This code needs porting to Python.

# /****************************************************************************
# **
# ** Copyright (C) 2016 The Qt Company Ltd.
# ** Contact: https://www.qt.io/licensing/
# **
# ** This file is part of the QtNetwork module of the Qt Toolkit.
# **
# ** $QT_BEGIN_LICENSE:BSD$
# ** Commercial License Usage
# ** Licensees holding valid commercial Qt licenses may use this file in
# ** accordance with the commercial license agreement provided with the
# ** Software or, alternatively, in accordance with the terms contained in
# ** a written agreement between you and The Qt Company. For licensing terms
# ** and conditions see https://www.qt.io/terms-conditions. For further
# ** information use the contact form at https://www.qt.io/contact-us.
# **
# ** BSD License Usage
# ** Alternatively, you may use this file under the terms of the BSD license
# ** as follows:
# **
# ** "Redistribution and use in source and binary forms, with or without
# ** modification, are permitted provided that the following conditions are
# ** met:
# **   * Redistributions of source code must retain the above copyright
# **     notice, this list of conditions and the following disclaimer.
# **   * Redistributions in binary form must reproduce the above copyright
# **     notice, this list of conditions and the following disclaimer in
# **     the documentation and/or other materials provided with the
# **     distribution.
# **   * Neither the name of The Qt Company Ltd nor the names of its
# **     contributors may be used to endorse or promote products derived
# **     from this software without specific prior written permission.
# **
# **
# ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
# **
# ** $QT_END_LICENSE$
# **
# ****************************************************************************/
# #include <QtCore>

# void slowOperation1()
# {
#     static char buf[256];
#     for (int i = 0; i < (1<<20); ++i)
#         buf[i % sizeof buf] = i;
# }

# void slowOperation2(int) { slowOperation1(); }

# void startExample()
# {
# //![0]
#     QElapsedTimer timer;
#     timer.start();

#     slowOperation1();

#     qDebug() << "The slow operation took" << timer.elapsed() << "milliseconds";
# //![0]
# }

# //![1]
# void executeSlowOperations(int timeout)
# {
#     QElapsedTimer timer;
#     timer.start();
#     slowOperation1();

#     int remainingTime = timeout - timer.elapsed();
#     if (remainingTime > 0)
#         slowOperation2(remainingTime);
# }
# //![1]

# //![2]
# void executeOperationsForTime(int ms)
# {
#     QElapsedTimer timer;
#     timer.start();

#     while (!timer.hasExpired(ms))
#         slowOperation1();
# }
# //![2]

# int restartExample()
# {
# //![3]
#     QElapsedTimer timer;

#     int count = 1;
#     timer.start();
#     do {
#         count *= 2;
#         slowOperation2(count);
#     } while (timer.restart() < 250);

#     return count;
# //![3]
# }

# int main(int argc, char **argv)
# {
#     QCoreApplication app(argc, argv);

#     startExample();
#     restartExample();
#     executeSlowOperations(5);
#     executeOperationsForTime(5);
# }

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:

# This code needs porting to Python.

# /****************************************************************************
# **
# ** Copyright (C) 2016 The Qt Company Ltd.
# ** Contact: https://www.qt.io/licensing/
# **
# ** This file is part of the QtNetwork module of the Qt Toolkit.
# **
# ** $QT_BEGIN_LICENSE:BSD$
# ** Commercial License Usage
# ** Licensees holding valid commercial Qt licenses may use this file in
# ** accordance with the commercial license agreement provided with the
# ** Software or, alternatively, in accordance with the terms contained in
# ** a written agreement between you and The Qt Company. For licensing terms
# ** and conditions see https://www.qt.io/terms-conditions. For further
# ** information use the contact form at https://www.qt.io/contact-us.
# **
# ** BSD License Usage
# ** Alternatively, you may use this file under the terms of the BSD license
# ** as follows:
# **
# ** "Redistribution and use in source and binary forms, with or without
# ** modification, are permitted provided that the following conditions are
# ** met:
# **   * Redistributions of source code must retain the above copyright
# **     notice, this list of conditions and the following disclaimer.
# **   * Redistributions in binary form must reproduce the above copyright
# **     notice, this list of conditions and the following disclaimer in
# **     the documentation and/or other materials provided with the
# **     distribution.
# **   * Neither the name of The Qt Company Ltd nor the names of its
# **     contributors may be used to endorse or promote products derived
# **     from this software without specific prior written permission.
# **
# **
# ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
# **
# ** $QT_END_LICENSE$
# **
# ****************************************************************************/
# #include <QtCore>

# void slowOperation1()
# {
#     static char buf[256];
#     for (int i = 0; i < (1<<20); ++i)
#         buf[i % sizeof buf] = i;
# }

# void slowOperation2(int) { slowOperation1(); }

# void startExample()
# {
# //![0]
#     QElapsedTimer timer;
#     timer.start();

#     slowOperation1();

#     qDebug() << "The slow operation took" << timer.elapsed() << "milliseconds";
# //![0]
# }

# //![1]
# void executeSlowOperations(int timeout)
# {
#     QElapsedTimer timer;
#     timer.start();
#     slowOperation1();

#     int remainingTime = timeout - timer.elapsed();
#     if (remainingTime > 0)
#         slowOperation2(remainingTime);
# }
# //![1]

# //![2]
# void executeOperationsForTime(int ms)
# {
#     QElapsedTimer timer;
#     timer.start();

#     while (!timer.hasExpired(ms))
#         slowOperation1();
# }
# //![2]

# int restartExample()
# {
# //![3]
#     QElapsedTimer timer;

#     int count = 1;
#     timer.start();
#     do {
#         count *= 2;
#         slowOperation2(count);
#     } while (timer.restart() < 250);

#     return count;
# //![3]
# }

# int main(int argc, char **argv)
# {
#     QCoreApplication app(argc, argv);

#     startExample();
#     restartExample();
#     executeSlowOperations(5);
#     executeOperationsForTime(5);
# }

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

Reference Clocks¶

QElapsedTimer will use the platform’s monotonic reference clock in all platforms that support it (see 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-saving 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 (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 clockType()).

32-bit overflows¶

Some of the clocks used by QElapsedTimer have a limited range and may overflow after hitting the upper limit (usually 32-bit). QElapsedTimer deals with this overflow issue and presents a consistent timing. However, when extracting the time since reference from QElapsedTimer, two different processes in the same machine may have different understanding of how much time has actually elapsed.

The information on which clocks types may overflow and how to remedy that issue is documented along with the clock types.

Enums¶

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 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 platforms. If the high-precision performance counter is available on Windows, the \ :sip:ref:`~PyQt5.QtCore.QElapsedTimer.ClockType.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’ 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.

MachAbsoluteTime¶

This clock type is based on the absolute time presented by Mach kernels, such as that found on macOS. This clock type is presented separately from MonotonicClock since macOS and iOS are also Unix systems 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 \ :sip:ref:`~PyQt5.QtCore.QElapsedTimer.ClockType.TickCounter` clock automatically, if this clock cannot be used.

This clock is monotonic and does not overflow.

Member

Value

Description

MachAbsoluteTime

3

The Mach kernel’s absolute time (macOS and iOS). This clock is monotonic and does not overflow.

MonotonicClock

1

The system’s monotonic clock, usually found in Unix systems. This clock is monotonic and does not overflow.

PerformanceCounter

4

The high-resolution performance counter provided by Windows. This clock is monotonic and does not overflow.

SystemTime

0

The human-readable system time. This clock is not monotonic.

TickCounter

2

The system’s tick counter, used on Windows systems. This clock may overflow.

Methods¶

__init__()

TODO


__init__(QElapsedTimer)

TODO


@staticmethod
clockType() → ClockType

TODO


elapsed() → int

TODO


__eq__(QElapsedTimer) → bool

TODO


__ge__(QElapsedTimer) → bool

TODO


hasExpired(int) → bool

TODO


invalidate()

TODO


@staticmethod
isMonotonic() → bool

TODO


isValid() → bool

TODO


__lt__(QElapsedTimer) → bool

TODO


msecsSinceReference() → int

TODO


msecsTo(QElapsedTimer) → int

TODO


__ne__(QElapsedTimer) → bool

TODO


nsecsElapsed() → int

TODO


restart() → int

TODO


secsTo(QElapsedTimer) → int

TODO


start()

TODO