The Linux Programming Interface

(nextflipdebug5) #1

186 Chapter 10


10.1 Calendar Time


Regardless of geographic location, UNIX systems represent time internally as a
measure of seconds since the Epoch; that is, since midnight on the morning of
1 January 1970, Universal Coordinated Time (UTC, previously known as Green-
wich Mean Time, or GMT). This is approximately the date when the UNIX system
came into being. Calendar time is stored in variables of type time_t, an integer type
specified by SUSv3.

On 32-bit Linux systems, time_t, which is a signed integer, can represent dates
in the range 13 December 1901 20:45:52 to 19 January 2038 03:14:07. (SUSv3
leaves the meaning of negative time_t values unspecified.) Thus, many current
32-bit UNIX systems face a theoretical Year 2038 problem, which they may
encounter before 2038, if they do calculations based on dates in the future.
This problem will be significantly alleviated by the fact that by 2038, probably
all UNIX systems will have long become 64-bit and beyond. However, 32-bit
embedded systems, which typically have a much longer lifespan than desktop
hardware, may still be afflicted by the problem. Furthermore, the problem will
remain for any legacy data and applications that maintain time in a 32-bit
time_t format.

The gettimeofday() system call returns the calendar time in the buffer pointed to by tv.

The tv argument is a pointer to a structure of the following form:

struct timeval {
time_t tv_sec; /* Seconds since 00:00:00, 1 Jan 1970 UTC */
suseconds_t tv_usec; /* Additional microseconds (long int) */
};

Although the tv_usec field affords microsecond precision, the accuracy of the value
it returns is determined by the architecture-dependent implementation. (The u in
tv_usec derives from the resemblance to the Greek letter μ (“mu”) used in the metric
system to denote one-millionth.) On modern x86-32 systems (i.e., Pentium systems
with a Timestamp Counter register that is incremented once at each CPU clock
cycle), gettimeofday() does provide microsecond accuracy.
The tz argument to gettimeofday() is a historical artifact. In older UNIX imple-
mentations, it was used to retrieve timezone information for the system. This argu-
ment is now obsolete and should always be specified as NULL.

#include <sys/time.h>

int gettimeofday(struct timeval *tv, struct timezone *tz);
Returns 0 on success, or –1 on error
Free download pdf