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 <a.samirh78@gmail.com>
(cherry picked from commit 61924c622acc5afd1e01dd65702e09a063928c5f)
Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>
This commit is contained in:
Thiago Macieira 2025-01-07 23:58:13 -03:00 committed by Qt Cherry-pick Bot
parent 715ae29080
commit c804fc386b

View File

@ -1687,20 +1687,24 @@ static QString formatLogMessage(QtMsgType type, const QMessageLogContext &contex
#endif #endif
} else if (token == timeTokenC) { } else if (token == timeTokenC) {
using namespace std::chrono; using namespace std::chrono;
auto formatElapsedTime = [](steady_clock::duration time) {
// we assume time > 0
auto ms = duration_cast<milliseconds>(time);
auto sec = duration_cast<seconds>(ms);
ms -= sec;
return QString::asprintf("%6lld.%03u", qint64(sec.count()), uint(ms.count()));
};
QString timeFormat = pattern->timeArgs.at(timeArgsIdx); QString timeFormat = pattern->timeArgs.at(timeArgsIdx);
timeArgsIdx++; timeArgsIdx++;
if (timeFormat == "process"_L1) { if (timeFormat == "process"_L1) {
auto elapsed = steady_clock::now() - pattern->appStartTime; message += formatElapsedTime(steady_clock::now() - pattern->appStartTime);
quint64 ms = duration_cast<milliseconds>(elapsed).count();
message.append(QString::asprintf("%6d.%03d", uint(ms / 1000), uint(ms % 1000)));
} else if (timeFormat == "boot"_L1) { } else if (timeFormat == "boot"_L1) {
// just print the milliseconds since the elapsed timer reference // just print the milliseconds since the elapsed timer reference
// like the Linux kernel does // like the Linux kernel does
qint64 ms = duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count(); message += formatElapsedTime(steady_clock::now().time_since_epoch());
message.append(QString::asprintf("%6d.%03d", uint(ms / 1000), uint(ms % 1000)));
#if QT_CONFIG(datestring) #if QT_CONFIG(datestring)
} else if (timeFormat.isEmpty()) { } else if (timeFormat.isEmpty()) {
message.append(QDateTime::currentDateTime().toString(Qt::ISODate)); message.append(QDateTime::currentDateTime().toString(Qt::ISODate));
} else { } else {
message.append(QDateTime::currentDateTime().toString(timeFormat)); message.append(QDateTime::currentDateTime().toString(timeFormat));
#endif // QT_CONFIG(datestring) #endif // QT_CONFIG(datestring)