Fix the way we get high-resolution time.

If we're not on Windows, use clock_gettime(CLOCK_REALTIME) *if* we have
it; otherwise, fall back on gettimeofday().

(Note: neither Linux, nor macOS, nor Windows necessarily "have"
particular APIs; particular *versions* of Linux distributions
(kernel+libc) have them, particular *versions* of macOS have them, and
particular *versions* of Windows+MSVC have them.

And Linux, Windows and macOS aren't the only platforms on which we run.)

Fixes #17101.
Guy Harris 2020-12-20 13:31:57 -08:00
parent 299d2f1ae5
commit ca99a821b4
3 changed files with 34 additions and 3 deletions

View File

check_symbol_exists("floorl" "math.h" HAVE_FLOORL)
# Check whether we have clock_gettime().
# It's not on Windows, so don't waste time checking for it.
# It's in newer POSIX, so some, but not all, UN*Xes have it.
if (NOT WIN32)
# POSIX - don't bother checking on Windows, as checks
# take time.
check_function_exists("clock_gettime" HAVE_CLOCK_GETTIME)
endif (NOT WIN32)
check_function_exists("getopt_long" HAVE_GETOPT_LONG)

View File

@ -40,6 +40,9 @@
/* Define to 1 if you have the <arpa/inet.h> header file. */
#cmakedefine HAVE_ARPA_INET_H 1
/* Define to 1 if you have the `clock_gettime` function. */
#cmakedefine HAVE_CLOCK_GETTIME 1
/* Define to 1 if you have the <fcntl.h> header file. */
#cmakedefine HAVE_FCNTL_H 1

View File

@ -10,6 +10,10 @@
#include "config.h"
#include <time.h>
#if !defined(_WIN32) && !defined(HAVE_CLOCK_GETTIME)
// For gettimeofday()
#include <sys/time.h>
#include "import_text_dialog.h"
@ -382,10 +386,21 @@ void ImportTextDialog::on_dateTimeLineEdit_textChanged(const QString &time_forma
char time_str[100];
QString timefmt = QString(time_format);
#ifdef _WIN32
timespec_get(&timenow, TIME_UTC); /* supported by Linux and Windows */
#if defined(_WIN32)
// At least some Windows C libraries have this.
// Some UN*X C libraries do, as well, but they might not
// show it unless you're requesting C11 - or C++17.
timespec_get(&timenow, TIME_UTC);
#elif defined(HAVE_CLOCK_GETTIME)
// Newer POSIX API. Some UN*Xes whose C libraries lack
// timespec_get() (C11) have this.
clock_gettime(CLOCK_REALTIME, &timenow);
clock_gettime(CLOCK_REALTIME, &timenow); /* supported by Linux and MacOS */
// Fall back on gettimeofday().
struct timeval usectimenow;
gettimeofday(&usectimenow, NULL);
timenow.tv_sec = usectimenow.tv_sec;
timenow.tv_nsec = usectimenow.tv_usec*1000;
/* On windows strftime/wcsftime does not support %s yet, this works on all OSs */
timefmt.replace(QString("%s"), QString::number(timenow.tv_sec));