1 /* Copyright (C) 1996 N.M. Maclaren
2 Copyright (C) 1996 The University of Cambridge
4 This includes all of the code needed to handle the time. It assumes rather
5 more than is defined by POSIX, unfortunately. Systems that do not have the
6 'X/Open' extensions may need changes. */
12 #include <sys/types.h>
21 #define MILLION_L 1000000l /* For conversion to/from timeval */
22 #define MILLION_D 1.0e6 /* Must be equal to MILLION_L */
26 double current_time (double offset) {
28 /* Get the current UTC time in seconds since the Epoch plus an offset (usually
29 the time from the beginning of the century to the Epoch!) */
31 struct timeval current;
34 if (gettimeofday(¤t,NULL))
35 fatal(1,"unable to read current machine/system time",NULL);
36 return offset+current.tv_sec+1.0e-6*current.tv_usec;
41 time_t convert_time (double value, int *millisecs) {
43 /* Convert the time to the ANSI C form. */
45 time_t result = (time_t)value;
47 if ((*millisecs = (int)(1000.0*(value-result))) >= 1000) {
56 void adjust_time (double difference, int immediate, double ignore) {
58 /* Adjust the current UTC time. This is portable, even if struct timeval uses
59 an unsigned long for tv_sec. */
61 struct timeval old, new, adjust, previous;
65 /* Start by converting to timeval format. Note that we have to cater for
66 negative, unsigned values. */
68 if ((n = (long)difference) > difference) --n;
70 adjust.tv_usec = (long)(MILLION_D*(difference-n));
72 if (gettimeofday(&old,NULL))
73 fatal(1,"unable to read machine/system time",NULL);
74 new.tv_sec = old.tv_sec+adjust.tv_sec;
75 new.tv_usec = (n = (long)old.tv_usec+(long)adjust.tv_usec);
77 new.tv_usec += MILLION_L;
79 } else if (n >= MILLION_L) {
80 new.tv_usec -= MILLION_L;
84 /* Now diagnose the situation if necessary, and perform the dirty deed. */
88 "Times: old=(%ld,%.6ld) new=(%ld,%.6ld) adjust=(%ld,%.6ld)\n",
89 (long)old.tv_sec,(long)old.tv_usec,
90 (long)new.tv_sec,(long)new.tv_usec,
91 (long)adjust.tv_sec,(long)adjust.tv_usec);
94 if (settimeofday(&new,NULL))
95 fatal(1,"unable to reset current system time",NULL);
100 if (adjtime(&adjust,&previous))
101 fatal(1,"unable to adjust current system time",NULL);
102 if (previous.tv_sec != 0 || previous.tv_usec != 0) {
103 sprintf(text,"(%ld,%.6ld)",
104 (long)previous.tv_sec,(long)previous.tv_usec);
105 if (previous.tv_sec+1.0e-6*previous.tv_usec > ignore)
106 fatal(0,"outstanding time adjustment %s",text);
108 fprintf(stderr,"%s: outstanding time adjustment %s\n",