Scientific Operations Bellum Gratia Artis

testing - 2015 - September - this message

[ previous , next ]

Subject: Re: [9fans] off topic - a good Git reference

From: Charles Forsyth <charles.forsyth@[REDACTED]>
Date: Wed, 30 Sep 2015 08:59:40 +0100
found text part

On 30 September 2015 at 08:47, Charles Forsyth 
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 
#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
 and call time(NULL) to get that, but where's the fun?