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 <thiago.macieira@intel.com>
(cherry picked from commit 4366487e79f84fb381e33207cbc7c28107aea561)
Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>
This commit is contained in:
Edward Welbourne 2023-11-14 17:14:24 +01:00 committed by Qt Cherry-pick Bot
parent ca80d4ff09
commit c298d56993

View File

@ -4974,7 +4974,7 @@ qint64 QDateTime::currentSecsSinceEpoch() noexcept
daysAfterEpoch * SECS_PER_DAY; daysAfterEpoch * SECS_PER_DAY;
} }
#elif defined(Q_OS_UNIX) #elif defined(Q_OS_UNIX) // Assume POSIX-compliant
QDate QDate::currentDate() QDate QDate::currentDate()
{ {
return QDateTime::currentDateTime().date(); return QDateTime::currentDateTime().date();
@ -4992,18 +4992,18 @@ QDateTime QDateTime::currentDateTime(const QTimeZone &zone)
qint64 QDateTime::currentMSecsSinceEpoch() noexcept qint64 QDateTime::currentMSecsSinceEpoch() noexcept
{ {
// posix compliant system struct timespec when;
// we have milliseconds if (clock_gettime(CLOCK_REALTIME, &when) == 0) // should always succeed
struct timeval tv; return when.tv_sec * MSECS_PER_SEC + (when.tv_nsec + 500'000) / 1'000'000;
gettimeofday(&tv, nullptr); Q_UNREACHABLE_RETURN(0);
return tv.tv_sec * MSECS_PER_SEC + tv.tv_usec / 1000;
} }
qint64 QDateTime::currentSecsSinceEpoch() noexcept qint64 QDateTime::currentSecsSinceEpoch() noexcept
{ {
struct timeval tv; struct timespec when;
gettimeofday(&tv, nullptr); if (clock_gettime(CLOCK_REALTIME, &when) == 0) // should always succeed
return tv.tv_sec; return when.tv_sec;
Q_UNREACHABLE_RETURN(0);
} }
#else #else
#error "What system is this?" #error "What system is this?"