QElapsedTimer timer;
timer.start();
slowOperation1();
qDebug() << "The slow operation took" << timer.elapsed() << "milliseconds";
http://doc.qt.io/qt-5/qelapsedtimer.html#invalidate
qDebug()
之后我想停止这个计时器。我在那里看不到停止功能,也没有单击属性。
出路是什么?
答案 0 :(得分:5)
您无法停止QElapsedTimer
,因为没有计时器。当您调用方法start()
时,QElapsedTimer
会保存当前时间。
void QElapsedTimer::start() Q_DECL_NOTHROW
{
restart();
}
qint64 QElapsedTimer::restart() Q_DECL_NOTHROW
{
qint64 old = t1;
t1 = QDateTime::currentMSecsSinceEpoch();
t2 = 0;
return t1 - old;
}
经过时,它会再次获得当前时间,并计算差异。
qint64 QElapsedTimer::elapsed() const Q_DECL_NOTHROW
{
return QDateTime::currentMSecsSinceEpoch() - t1;
}
答案 1 :(得分:1)
QElapsedTimer将在所有支持平台的平台上使用平台的单调参考时钟。这样做还有一个好处,就是QElapsedTimer不受时间调整的影响,例如用户可以校正时间。同样不同于QTime,QElapsedTimer不受时区设置的更改(例如夏令时)的影响。 https://doc.qt.io/qt-5/qelapsedtimer.html#details
答案 2 :(得分:1)
我需要一个不计算暂停时间的经过计时器,所以我想出了以下方法: ElapsedTimer.hpp:
#pragma once
#include <time.h>
#include <cstdio>
#include <cstdint>
#include <cstring>
#include <errno.h>
namespace your_namespace {
class ElapsedTimer {
public:
ElapsedTimer();
~ElapsedTimer();
void Continue();
void Pause();
int64_t elapsed_ms();
private:
struct timespec start_ = {};
int64_t worked_time_ = 0;
/// CLOCK_MONOTONIC_COARSE is faster but less precise
/// CLOCK_MONOTONIC_RAW is slower but more precise
const clockid_t clock_type_ = CLOCK_MONOTONIC_RAW;
};
}
ElapsedTimer.cpp:
#include "ElapsedTimer.hpp"
namespace your_namespace {
ElapsedTimer::ElapsedTimer() {}
ElapsedTimer::~ElapsedTimer() {}
inline int64_t GetDiffMs(const timespec &end, const timespec &start) {
return (end.tv_sec - start.tv_sec) * 1000L + (end.tv_nsec - start.tv_nsec) / 1000000L;
}
void ElapsedTimer::Continue()
{
int status = clock_gettime(clock_type_, &start_);
if (status != 0)
printf("%s", strerror(errno));
}
int64_t ElapsedTimer::elapsed_ms()
{
const bool paused = (start_.tv_sec == 0 && start_.tv_nsec == 0);
if (paused)
return worked_time_;
struct timespec now;
int status = clock_gettime(clock_type_, &now);
if (status != 0)
printf("%s", strerror(errno));
const int64_t extra = GetDiffMs(now, start_);
return worked_time_ + extra;
}
void ElapsedTimer::Pause() {
struct timespec now;
int status = clock_gettime(clock_type_, &now);
if (status != 0)
printf("%s", strerror(errno));
worked_time_ += GetDiffMs(now, start_);
start_ = {};
}
}
用作:
my_namespace::ElapsedTimer timer;
timer.Continue(); // starts recording the amount of time
timer.Pause();// stops recording time
///do something else
timer.Continue();// resumes recording time
/// and at any time call this to find out how many
/// ms passed excluding the paused time:
int64_t passed_ms = timer.elapsed_ms();