On 30 September 2015 at 08:47, Charles Forsyth <[email protected]>
wrote:
> I was being sarcastic about the portability of so much contemporary C code.
Here's a small but representative example.
#if HAVE_SYS_TIME_H
#include <sys/time.h
#elif HAVE_TIME_H
#include <time.h>
#endif
#if HAVE_SYS_CLOCK_GETTIME
time_t
time_now(void)
{
struct timespec timespec_value;
(void) clock_gettime(CLOCK_REALTIME, ×pec_value);
return timespec_value.tv_seconds;
}
#elif HAVE_SYS_GETTIMEOFDAY
time_t
time_now(void)
{
struct timeval timeval_value;
(void) gettimeofday(&timeval_value, (struct timezone *) NULL);
return timeval_value.tv_seconds;
}
#elif HAVE_SYS_TIME
time_t
time_now(void)
{
time_t seconds_since_epoch;
(void) time(&seconds_since_epoch);
return seconds_since_epoch;
}
#endif
./configure # work out which HAVE_... definitions to use
Usually there are a few more alternatives enumerated. Surprisingly often,
the microseconds or nanoseconds
value is discarded, to get the seconds. You could just use #include
<time.h> and call time(NULL) to get that, but where's the fun?