core/elapsedtimer: add ElapsedTimer

This commit is contained in:
outfoxxed 2024-06-04 13:14:39 -07:00
parent 37fecfc990
commit bcb2a66174
Signed by: outfoxxed
GPG Key ID: 4C88A185FB89301E
2 changed files with 67 additions and 0 deletions

22
src/core/elapsedtimer.cpp Normal file
View File

@ -0,0 +1,22 @@
#include "elapsedtimer.hpp"
#include <qtypes.h>
ElapsedTimer::ElapsedTimer() { this->timer.start(); }
qreal ElapsedTimer::elapsed() { return static_cast<qreal>(this->elapsedNs()) / 1000000000.0; }
qreal ElapsedTimer::restart() { return static_cast<qreal>(this->restartNs()) / 1000000000.0; }
qint64 ElapsedTimer::elapsedMs() { return this->timer.elapsed(); }
qint64 ElapsedTimer::restartMs() { return this->timer.restart(); }
qint64 ElapsedTimer::elapsedNs() { return this->timer.nsecsElapsed(); }
qint64 ElapsedTimer::restartNs() {
// see qelapsedtimer.cpp
auto old = this->timer;
this->timer.start();
return old.durationTo(this->timer).count();
}

45
src/core/elapsedtimer.hpp Normal file
View File

@ -0,0 +1,45 @@
#pragma once
#include <qelapsedtimer.h>
#include <qobject.h>
#include <qqmlintegration.h>
#include <qtmetamacros.h>
#include <qtypes.h>
///! Measures time between events
/// The ElapsedTimer measures time since its last restart, and is useful
/// for determining the time between events that don't supply it.
class ElapsedTimer: public QObject {
Q_OBJECT;
QML_ELEMENT;
public:
explicit ElapsedTimer();
/// Return the number of seconds since the timer was last
/// started or restarted, with nanosecond precision.
Q_INVOKABLE qreal elapsed();
/// Restart the timer, returning the number of seconds since
/// the timer was last started or restarted, with nanosecond precision.
Q_INVOKABLE qreal restart();
/// Return the number of milliseconds since the timer was last
/// started or restarted.
Q_INVOKABLE qint64 elapsedMs();
/// Restart the timer, returning the number of milliseconds since
/// the timer was last started or restarted.
Q_INVOKABLE qint64 restartMs();
/// Return the number of nanoseconds since the timer was last
/// started or restarted.
Q_INVOKABLE qint64 elapsedNs();
/// Restart the timer, returning the number of nanoseconds since
/// the timer was last started or restarted.
Q_INVOKABLE qint64 restartNs();
private:
QElapsedTimer timer;
};