Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does difftime() return a double?

Tags:

c

posix

From difftime()'s man page:

double difftime(time_t time1, time_t time0);

The difftime() function returns the number of seconds elapsed between time time1 and time time0, represented as a double.

Since 'number of seconds' doesn't require floating-point numbers, why does this function return a double?

like image 552
Zaxter Avatar asked Dec 24 '15 21:12

Zaxter


2 Answers

This documentation is more clear on the point:

On POSIX systems, time_t is measured in seconds, and difftime is equivalent to arithmetic subtraction, but C and C++ allow fractional units for time_t.

Although POSIX requires time_t to be an integer type, for non-POSIX systems it is possible that this can return fractional seconds.

like image 109
J... Avatar answered Oct 16 '22 18:10

J...


C allows for various scalar numbers (integers, floating point) to represent time. It needs to be a "... real types capable of representing times" C11 §7.27.1 3,

The range and precision of times representable in clock_t and time_t are implementation-defined. C11dr §7.27.1 4

The difference between 2 time_t values, as a double affords a vary wide range and precision.

OP, "Since 'number of seconds' doesn't require floating-point numbers, why does this function return a double?


[Edit] Linux/posix might not use fractions of seconds, but other systems have done so. The C standard that defines difftime() choose double and that accommodates an integer accumulation of seconds as well as other OS implementations.

like image 44
chux - Reinstate Monica Avatar answered Oct 16 '22 17:10

chux - Reinstate Monica