From c298d569933322bebd42c06aef892a228de715f9 Mon Sep 17 00:00:00 2001 From: Edward Welbourne Date: Tue, 14 Nov 2023 17:14:24 +0100 Subject: [PATCH] Change POSIX current time query to use clock_gettime() As noted on its man-page, POSIX.1-2008 marks gettimeofday() as obsolete, recommending the use of clock_gettime(2) instead. So do that. Also check the return value - albeit all we can do on failure (which should not happen) is assert. Pick-to: 6.5 Change-Id: Id5d6922c974b87f09531d549d692b051c32388ee Reviewed-by: Thiago Macieira (cherry picked from commit 4366487e79f84fb381e33207cbc7c28107aea561) Reviewed-by: Qt Cherry-pick Bot --- src/corelib/time/qdatetime.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/corelib/time/qdatetime.cpp b/src/corelib/time/qdatetime.cpp index 8b0ce0f6d5b..553673da804 100644 --- a/src/corelib/time/qdatetime.cpp +++ b/src/corelib/time/qdatetime.cpp @@ -4974,7 +4974,7 @@ qint64 QDateTime::currentSecsSinceEpoch() noexcept daysAfterEpoch * SECS_PER_DAY; } -#elif defined(Q_OS_UNIX) +#elif defined(Q_OS_UNIX) // Assume POSIX-compliant QDate QDate::currentDate() { return QDateTime::currentDateTime().date(); @@ -4992,18 +4992,18 @@ QDateTime QDateTime::currentDateTime(const QTimeZone &zone) qint64 QDateTime::currentMSecsSinceEpoch() noexcept { - // posix compliant system - // we have milliseconds - struct timeval tv; - gettimeofday(&tv, nullptr); - return tv.tv_sec * MSECS_PER_SEC + tv.tv_usec / 1000; + struct timespec when; + if (clock_gettime(CLOCK_REALTIME, &when) == 0) // should always succeed + return when.tv_sec * MSECS_PER_SEC + (when.tv_nsec + 500'000) / 1'000'000; + Q_UNREACHABLE_RETURN(0); } qint64 QDateTime::currentSecsSinceEpoch() noexcept { - struct timeval tv; - gettimeofday(&tv, nullptr); - return tv.tv_sec; + struct timespec when; + if (clock_gettime(CLOCK_REALTIME, &when) == 0) // should always succeed + return when.tv_sec; + Q_UNREACHABLE_RETURN(0); } #else #error "What system is this?"