From c804fc386bd584a5bed81d2da85422b935d40bb6 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Tue, 7 Jan 2025 23:58:13 -0300 Subject: [PATCH] QMessagePattern: merge and improve %{time}-printing code All modern compilers implement divisions and modulus via multiplications and shift, so the codegen is practically the same (three multiplications in total). But the new code allows more than 136 years of uptime (49710 days). Drive-by fix indentation in nearby line. Change-Id: Iea806bd7dfac1f852c66fffd41c2ac6660e7cc65 Reviewed-by: Ahmad Samir (cherry picked from commit 61924c622acc5afd1e01dd65702e09a063928c5f) Reviewed-by: Qt Cherry-pick Bot --- src/corelib/global/qlogging.cpp | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/corelib/global/qlogging.cpp b/src/corelib/global/qlogging.cpp index 87077d865fb..97ea164235f 100644 --- a/src/corelib/global/qlogging.cpp +++ b/src/corelib/global/qlogging.cpp @@ -1687,20 +1687,24 @@ static QString formatLogMessage(QtMsgType type, const QMessageLogContext &contex #endif } else if (token == timeTokenC) { using namespace std::chrono; + auto formatElapsedTime = [](steady_clock::duration time) { + // we assume time > 0 + auto ms = duration_cast(time); + auto sec = duration_cast(ms); + ms -= sec; + return QString::asprintf("%6lld.%03u", qint64(sec.count()), uint(ms.count())); + }; QString timeFormat = pattern->timeArgs.at(timeArgsIdx); timeArgsIdx++; if (timeFormat == "process"_L1) { - auto elapsed = steady_clock::now() - pattern->appStartTime; - quint64 ms = duration_cast(elapsed).count(); - message.append(QString::asprintf("%6d.%03d", uint(ms / 1000), uint(ms % 1000))); + message += formatElapsedTime(steady_clock::now() - pattern->appStartTime); } else if (timeFormat == "boot"_L1) { // just print the milliseconds since the elapsed timer reference // like the Linux kernel does - qint64 ms = duration_cast(steady_clock::now().time_since_epoch()).count(); - message.append(QString::asprintf("%6d.%03d", uint(ms / 1000), uint(ms % 1000))); + message += formatElapsedTime(steady_clock::now().time_since_epoch()); #if QT_CONFIG(datestring) } else if (timeFormat.isEmpty()) { - message.append(QDateTime::currentDateTime().toString(Qt::ISODate)); + message.append(QDateTime::currentDateTime().toString(Qt::ISODate)); } else { message.append(QDateTime::currentDateTime().toString(timeFormat)); #endif // QT_CONFIG(datestring)