forked from lattera/glibc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime.texi
2892 lines (2350 loc) · 113 KB
/
time.texi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
@node Date and Time, Resource Usage And Limitation, Arithmetic, Top
@c %MENU% Functions for getting the date and time and formatting them nicely
@chapter Date and Time
This chapter describes functions for manipulating dates and times,
including functions for determining what time it is and conversion
between different time representations.
@menu
* Time Basics:: Concepts and definitions.
* Elapsed Time:: Data types to represent elapsed times
* Processor And CPU Time:: Time a program has spent executing.
* Calendar Time:: Manipulation of ``real'' dates and times.
* Setting an Alarm:: Sending a signal after a specified time.
* Sleeping:: Waiting for a period of time.
@end menu
@node Time Basics
@section Time Basics
@cindex time
Discussing time in a technical manual can be difficult because the word
``time'' in English refers to lots of different things. In this manual,
we use a rigorous terminology to avoid confusion, and the only thing we
use the simple word ``time'' for is to talk about the abstract concept.
A @dfn{calendar time} is a point in the time continuum, for example
November 4, 1990, at 18:02.5 UTC. Sometimes this is called ``absolute
time''.
@cindex calendar time
We don't speak of a ``date'', because that is inherent in a calendar
time.
@cindex date
An @dfn{interval} is a contiguous part of the time continuum between two
calendar times, for example the hour between 9:00 and 10:00 on July 4,
1980.
@cindex interval
An @dfn{elapsed time} is the length of an interval, for example, 35
minutes. People sometimes sloppily use the word ``interval'' to refer
to the elapsed time of some interval.
@cindex elapsed time
@cindex time, elapsed
An @dfn{amount of time} is a sum of elapsed times, which need not be of
any specific intervals. For example, the amount of time it takes to
read a book might be 9 hours, independently of when and in how many
sittings it is read.
A @dfn{period} is the elapsed time of an interval between two events,
especially when they are part of a sequence of regularly repeating
events.
@cindex period of time
@dfn{CPU time} is like calendar time, except that it is based on the
subset of the time continuum when a particular process is actively
using a CPU. CPU time is, therefore, relative to a process.
@cindex CPU time
@dfn{Processor time} is an amount of time that a CPU is in use. In
fact, it's a basic system resource, since there's a limit to how much
can exist in any given interval (that limit is the elapsed time of the
interval times the number of CPUs in the processor). People often call
this CPU time, but we reserve the latter term in this manual for the
definition above.
@cindex processor time
@node Elapsed Time
@section Elapsed Time
@cindex elapsed time
One way to represent an elapsed time is with a simple arithmetic data
type, as with the following function to compute the elapsed time between
two calendar times. This function is declared in @file{time.h}.
@deftypefun double difftime (time_t @var{time1}, time_t @var{time0})
@standards{ISO, time.h}
@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
The @code{difftime} function returns the number of seconds of elapsed
time between calendar time @var{time1} and calendar time @var{time0}, as
a value of type @code{double}. The difference ignores leap seconds
unless leap second support is enabled.
In @theglibc{}, you can simply subtract @code{time_t} values. But on
other systems, the @code{time_t} data type might use some other encoding
where subtraction doesn't work directly.
@end deftypefun
@Theglibc{} provides two data types specifically for representing
an elapsed time. They are used by various @glibcadj{} functions, and
you can use them for your own purposes too. They're exactly the same
except that one has a resolution in microseconds, and the other, newer
one, is in nanoseconds.
@deftp {Data Type} {struct timeval}
@standards{BSD, sys/time.h}
@cindex timeval
The @code{struct timeval} structure represents an elapsed time. It is
declared in @file{sys/time.h} and has the following members:
@table @code
@item time_t tv_sec
This represents the number of whole seconds of elapsed time.
@item long int tv_usec
This is the rest of the elapsed time (a fraction of a second),
represented as the number of microseconds. It is always less than one
million.
@end table
@end deftp
@deftp {Data Type} {struct timespec}
@standards{POSIX.1, sys/time.h}
@cindex timespec
The @code{struct timespec} structure represents an elapsed time. It is
declared in @file{time.h} and has the following members:
@table @code
@item time_t tv_sec
This represents the number of whole seconds of elapsed time.
@item long int tv_nsec
This is the rest of the elapsed time (a fraction of a second),
represented as the number of nanoseconds. It is always less than one
billion.
@end table
@end deftp
It is often necessary to subtract two values of type @w{@code{struct
timeval}} or @w{@code{struct timespec}}. Here is the best way to do
this. It works even on some peculiar operating systems where the
@code{tv_sec} member has an unsigned type.
@smallexample
@include timeval_subtract.c.texi
@end smallexample
Common functions that use @code{struct timeval} are @code{gettimeofday}
and @code{settimeofday}.
There are no @glibcadj{} functions specifically oriented toward
dealing with elapsed times, but the calendar time, processor time, and
alarm and sleeping functions have a lot to do with them.
@node Processor And CPU Time
@section Processor And CPU Time
If you're trying to optimize your program or measure its efficiency,
it's very useful to know how much processor time it uses. For that,
calendar time and elapsed times are useless because a process may spend
time waiting for I/O or for other processes to use the CPU. However,
you can get the information with the functions in this section.
CPU time (@pxref{Time Basics}) is represented by the data type
@code{clock_t}, which is a number of @dfn{clock ticks}. It gives the
total amount of time a process has actively used a CPU since some
arbitrary event. On @gnusystems{}, that event is the creation of the
process. While arbitrary in general, the event is always the same event
for any particular process, so you can always measure how much time on
the CPU a particular computation takes by examining the process' CPU
time before and after the computation.
@cindex CPU time
@cindex clock ticks
@cindex ticks, clock
On @gnulinuxhurdsystems{}, @code{clock_t} is equivalent to @code{long int} and
@code{CLOCKS_PER_SEC} is an integer value. But in other systems, both
@code{clock_t} and the macro @code{CLOCKS_PER_SEC} can be either integer
or floating-point types. Casting CPU time values to @code{double}, as
in the example above, makes sure that operations such as arithmetic and
printing work properly and consistently no matter what the underlying
representation is.
Note that the clock can wrap around. On a 32bit system with
@code{CLOCKS_PER_SEC} set to one million this function will return the
same value approximately every 72 minutes.
For additional functions to examine a process' use of processor time,
and to control it, see @ref{Resource Usage And Limitation}.
@menu
* CPU Time:: The @code{clock} function.
* Processor Time:: The @code{times} function.
@end menu
@node CPU Time
@subsection CPU Time Inquiry
To get a process' CPU time, you can use the @code{clock} function. This
facility is declared in the header file @file{time.h}.
@pindex time.h
In typical usage, you call the @code{clock} function at the beginning
and end of the interval you want to time, subtract the values, and then
divide by @code{CLOCKS_PER_SEC} (the number of clock ticks per second)
to get processor time, like this:
@smallexample
@group
#include <time.h>
clock_t start, end;
double cpu_time_used;
start = clock();
@dots{} /* @r{Do the work.} */
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
@end group
@end smallexample
Do not use a single CPU time as an amount of time; it doesn't work that
way. Either do a subtraction as shown above or query processor time
directly. @xref{Processor Time}.
Different computers and operating systems vary wildly in how they keep
track of CPU time. It's common for the internal processor clock
to have a resolution somewhere between a hundredth and millionth of a
second.
@deftypevr Macro int CLOCKS_PER_SEC
@standards{ISO, time.h}
The value of this macro is the number of clock ticks per second measured
by the @code{clock} function. POSIX requires that this value be one
million independent of the actual resolution.
@end deftypevr
@deftp {Data Type} clock_t
@standards{ISO, time.h}
This is the type of the value returned by the @code{clock} function.
Values of type @code{clock_t} are numbers of clock ticks.
@end deftp
@deftypefun clock_t clock (void)
@standards{ISO, time.h}
@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
@c On Hurd, this calls task_info twice and adds user and system time
@c from both basic and thread time info structs. On generic posix,
@c calls times and adds utime and stime. On bsd, calls getrusage and
@c safely converts stime and utime to clock. On linux, calls
@c clock_gettime.
This function returns the calling process' current CPU time. If the CPU
time is not available or cannot be represented, @code{clock} returns the
value @code{(clock_t)(-1)}.
@end deftypefun
@node Processor Time
@subsection Processor Time Inquiry
The @code{times} function returns information about a process'
consumption of processor time in a @w{@code{struct tms}} object, in
addition to the process' CPU time. @xref{Time Basics}. You should
include the header file @file{sys/times.h} to use this facility.
@cindex processor time
@cindex CPU time
@pindex sys/times.h
@deftp {Data Type} {struct tms}
@standards{POSIX.1, sys/times.h}
The @code{tms} structure is used to return information about process
times. It contains at least the following members:
@table @code
@item clock_t tms_utime
This is the total processor time the calling process has used in
executing the instructions of its program.
@item clock_t tms_stime
This is the processor time the system has used on behalf of the calling
process.
@item clock_t tms_cutime
This is the sum of the @code{tms_utime} values and the @code{tms_cutime}
values of all terminated child processes of the calling process, whose
status has been reported to the parent process by @code{wait} or
@code{waitpid}; see @ref{Process Completion}. In other words, it
represents the total processor time used in executing the instructions
of all the terminated child processes of the calling process, excluding
child processes which have not yet been reported by @code{wait} or
@code{waitpid}.
@cindex child process
@item clock_t tms_cstime
This is similar to @code{tms_cutime}, but represents the total processor
time the system has used on behalf of all the terminated child processes
of the calling process.
@end table
All of the times are given in numbers of clock ticks. Unlike CPU time,
these are the actual amounts of time; not relative to any event.
@xref{Creating a Process}.
@end deftp
@deftypevr Macro int CLK_TCK
@standards{POSIX.1, time.h}
This is an obsolete name for the number of clock ticks per second. Use
@code{sysconf (_SC_CLK_TCK)} instead.
@end deftypevr
@deftypefun clock_t times (struct tms *@var{buffer})
@standards{POSIX.1, sys/times.h}
@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
@c On HURD, this calls task_info twice, for basic and thread times info,
@c adding user and system times into tms, and then gettimeofday, to
@c compute the real time. On BSD, it calls getclktck, getrusage (twice)
@c and time. On Linux, it's a syscall with special handling to account
@c for clock_t counts that look like error values.
The @code{times} function stores the processor time information for
the calling process in @var{buffer}.
The return value is the number of clock ticks since an arbitrary point
in the past, e.g. since system start-up. @code{times} returns
@code{(clock_t)(-1)} to indicate failure.
@end deftypefun
@strong{Portability Note:} The @code{clock} function described in
@ref{CPU Time} is specified by the @w{ISO C} standard. The
@code{times} function is a feature of POSIX.1. On @gnusystems{}, the
CPU time is defined to be equivalent to the sum of the @code{tms_utime}
and @code{tms_stime} fields returned by @code{times}.
@node Calendar Time
@section Calendar Time
This section describes facilities for keeping track of calendar time.
@xref{Time Basics}.
@Theglibc{} represents calendar time three ways:
@itemize @bullet
@item
@dfn{Simple time} (the @code{time_t} data type) is a compact
representation, typically giving the number of seconds of elapsed time
since some implementation-specific base time.
@cindex simple time
@item
There is also a "high-resolution time" representation. Like simple
time, this represents a calendar time as an elapsed time since a base
time, but instead of measuring in whole seconds, it uses a @code{struct
timeval} data type, which includes fractions of a second. Use this time
representation instead of simple time when you need greater precision.
@cindex high-resolution time
@item
@dfn{Local time} or @dfn{broken-down time} (the @code{struct tm} data
type) represents a calendar time as a set of components specifying the
year, month, and so on in the Gregorian calendar, for a specific time
zone. This calendar time representation is usually used only to
communicate with people.
@cindex local time
@cindex broken-down time
@cindex Gregorian calendar
@cindex calendar, Gregorian
@end itemize
@menu
* Simple Calendar Time:: Facilities for manipulating calendar time.
* High-Resolution Calendar:: A time representation with greater precision.
* Broken-down Time:: Facilities for manipulating local time.
* High Accuracy Clock:: Maintaining a high accuracy system clock.
* Formatting Calendar Time:: Converting times to strings.
* Parsing Date and Time:: Convert textual time and date information back
into broken-down time values.
* TZ Variable:: How users specify the time zone.
* Time Zone Functions:: Functions to examine or specify the time zone.
* Time Functions Example:: An example program showing use of some of
the time functions.
@end menu
@node Simple Calendar Time
@subsection Simple Calendar Time
This section describes the @code{time_t} data type for representing calendar
time as simple time, and the functions which operate on simple time objects.
These facilities are declared in the header file @file{time.h}.
@pindex time.h
@cindex epoch
@deftp {Data Type} time_t
@standards{ISO, time.h}
This is the data type used to represent simple time. Sometimes, it also
represents an elapsed time. When interpreted as a calendar time value,
it represents the number of seconds elapsed since 00:00:00 on January 1,
1970, Coordinated Universal Time. (This calendar time is sometimes
referred to as the @dfn{epoch}.) POSIX requires that this count not
include leap seconds, but on some systems this count includes leap seconds
if you set @code{TZ} to certain values (@pxref{TZ Variable}).
Note that a simple time has no concept of local time zone. Calendar
Time @var{T} is the same instant in time regardless of where on the
globe the computer is.
In @theglibc{}, @code{time_t} is equivalent to @code{long int}.
In other systems, @code{time_t} might be either an integer or
floating-point type.
@end deftp
The function @code{difftime} tells you the elapsed time between two
simple calendar times, which is not always as easy to compute as just
subtracting. @xref{Elapsed Time}.
@deftypefun time_t time (time_t *@var{result})
@standards{ISO, time.h}
@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
The @code{time} function returns the current calendar time as a value of
type @code{time_t}. If the argument @var{result} is not a null pointer,
the calendar time value is also stored in @code{*@var{result}}. If the
current calendar time is not available, the value
@w{@code{(time_t)(-1)}} is returned.
@end deftypefun
@c The GNU C library implements stime() with a call to settimeofday() on
@c Linux.
@deftypefun int stime (const time_t *@var{newtime})
@standards{SVID, time.h}
@standards{XPG, time.h}
@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
@c On unix, this is implemented in terms of settimeofday.
@code{stime} sets the system clock, i.e., it tells the system that the
current calendar time is @var{newtime}, where @code{newtime} is
interpreted as described in the above definition of @code{time_t}.
@code{settimeofday} is a newer function which sets the system clock to
better than one second precision. @code{settimeofday} is generally a
better choice than @code{stime}. @xref{High-Resolution Calendar}.
Only the superuser can set the system clock.
If the function succeeds, the return value is zero. Otherwise, it is
@code{-1} and @code{errno} is set accordingly:
@table @code
@item EPERM
The process is not superuser.
@end table
@end deftypefun
@node High-Resolution Calendar
@subsection High-Resolution Calendar
The @code{time_t} data type used to represent simple times has a
resolution of only one second. Some applications need more precision.
So, @theglibc{} also contains functions which are capable of
representing calendar times to a higher resolution than one second. The
functions and the associated data types described in this section are
declared in @file{sys/time.h}.
@pindex sys/time.h
@deftp {Data Type} {struct timezone}
@standards{BSD, sys/time.h}
The @code{struct timezone} structure is used to hold minimal information
about the local time zone. It has the following members:
@table @code
@item int tz_minuteswest
This is the number of minutes west of UTC.
@item int tz_dsttime
If nonzero, Daylight Saving Time applies during some part of the year.
@end table
The @code{struct timezone} type is obsolete and should never be used.
Instead, use the facilities described in @ref{Time Zone Functions}.
@end deftp
@deftypefun int gettimeofday (struct timeval *@var{tp}, struct timezone *@var{tzp})
@standards{BSD, sys/time.h}
@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
@c On most GNU/Linux systems this is a direct syscall, but the posix/
@c implementation (not used on GNU/Linux or GNU/Hurd) relies on time and
@c localtime_r, saving and restoring tzname in an unsafe manner.
@c On some GNU/Linux variants, ifunc resolvers are used in shared libc
@c for vdso resolution. ifunc-vdso-revisit.
The @code{gettimeofday} function returns the current calendar time as
the elapsed time since the epoch in the @code{struct timeval} structure
indicated by @var{tp}. (@pxref{Elapsed Time} for a description of
@code{struct timeval}). Information about the time zone is returned in
the structure pointed to by @var{tzp}. If the @var{tzp} argument is a null
pointer, time zone information is ignored.
The return value is @code{0} on success and @code{-1} on failure. The
following @code{errno} error condition is defined for this function:
@table @code
@item ENOSYS
The operating system does not support getting time zone information, and
@var{tzp} is not a null pointer. @gnusystems{} do not
support using @w{@code{struct timezone}} to represent time zone
information; that is an obsolete feature of 4.3 BSD.
Instead, use the facilities described in @ref{Time Zone Functions}.
@end table
@end deftypefun
@deftypefun int settimeofday (const struct timeval *@var{tp}, const struct timezone *@var{tzp})
@standards{BSD, sys/time.h}
@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
@c On HURD, it calls host_set_time with a privileged port. On other
@c unix systems, it's a syscall.
The @code{settimeofday} function sets the current calendar time in the
system clock according to the arguments. As for @code{gettimeofday},
the calendar time is represented as the elapsed time since the epoch.
As for @code{gettimeofday}, time zone information is ignored if
@var{tzp} is a null pointer.
You must be a privileged user in order to use @code{settimeofday}.
Some kernels automatically set the system clock from some source such as
a hardware clock when they start up. Others, including Linux, place the
system clock in an ``invalid'' state (in which attempts to read the clock
fail). A call of @code{stime} removes the system clock from an invalid
state, and system startup scripts typically run a program that calls
@code{stime}.
@code{settimeofday} causes a sudden jump forwards or backwards, which
can cause a variety of problems in a system. Use @code{adjtime} (below)
to make a smooth transition from one time to another by temporarily
speeding up or slowing down the clock.
With a Linux kernel, @code{adjtimex} does the same thing and can also
make permanent changes to the speed of the system clock so it doesn't
need to be corrected as often.
The return value is @code{0} on success and @code{-1} on failure. The
following @code{errno} error conditions are defined for this function:
@table @code
@item EPERM
This process cannot set the clock because it is not privileged.
@item ENOSYS
The operating system does not support setting time zone information, and
@var{tzp} is not a null pointer.
@end table
@end deftypefun
@c On Linux, GNU libc implements adjtime() as a call to adjtimex().
@deftypefun int adjtime (const struct timeval *@var{delta}, struct timeval *@var{olddelta})
@standards{BSD, sys/time.h}
@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
@c On hurd and mach, call host_adjust_time with a privileged port. On
@c Linux, it's implemented in terms of adjtimex. On other unixen, it's
@c a syscall.
This function speeds up or slows down the system clock in order to make
a gradual adjustment. This ensures that the calendar time reported by
the system clock is always monotonically increasing, which might not
happen if you simply set the clock.
The @var{delta} argument specifies a relative adjustment to be made to
the clock time. If negative, the system clock is slowed down for a
while until it has lost this much elapsed time. If positive, the system
clock is speeded up for a while.
If the @var{olddelta} argument is not a null pointer, the @code{adjtime}
function returns information about any previous time adjustment that
has not yet completed.
This function is typically used to synchronize the clocks of computers
in a local network. You must be a privileged user to use it.
With a Linux kernel, you can use the @code{adjtimex} function to
permanently change the clock speed.
The return value is @code{0} on success and @code{-1} on failure. The
following @code{errno} error condition is defined for this function:
@table @code
@item EPERM
You do not have privilege to set the time.
@end table
@end deftypefun
@strong{Portability Note:} The @code{gettimeofday}, @code{settimeofday},
and @code{adjtime} functions are derived from BSD.
Symbols for the following function are declared in @file{sys/timex.h}.
@deftypefun int adjtimex (struct timex *@var{timex})
@standards{GNU, sys/timex.h}
@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
@c It's a syscall, only available on linux.
@code{adjtimex} is functionally identical to @code{ntp_adjtime}.
@xref{High Accuracy Clock}.
This function is present only with a Linux kernel.
@end deftypefun
@node Broken-down Time
@subsection Broken-down Time
@cindex broken-down time
@cindex calendar time and broken-down time
Calendar time is represented by the usual @glibcadj{} functions as an
elapsed time since a fixed base calendar time. This is convenient for
computation, but has no relation to the way people normally think of
calendar time. By contrast, @dfn{broken-down time} is a binary
representation of calendar time separated into year, month, day, and so
on. Broken-down time values are not useful for calculations, but they
are useful for printing human readable time information.
A broken-down time value is always relative to a choice of time
zone, and it also indicates which time zone that is.
The symbols in this section are declared in the header file @file{time.h}.
@deftp {Data Type} {struct tm}
@standards{ISO, time.h}
This is the data type used to represent a broken-down time. The structure
contains at least the following members, which can appear in any order.
@table @code
@item int tm_sec
This is the number of full seconds since the top of the minute (normally
in the range @code{0} through @code{59}, but the actual upper limit is
@code{60}, to allow for leap seconds if leap second support is
available).
@cindex leap second
@item int tm_min
This is the number of full minutes since the top of the hour (in the
range @code{0} through @code{59}).
@item int tm_hour
This is the number of full hours past midnight (in the range @code{0} through
@code{23}).
@item int tm_mday
This is the ordinal day of the month (in the range @code{1} through @code{31}).
Watch out for this one! As the only ordinal number in the structure, it is
inconsistent with the rest of the structure.
@item int tm_mon
This is the number of full calendar months since the beginning of the
year (in the range @code{0} through @code{11}). Watch out for this one!
People usually use ordinal numbers for month-of-year (where January = 1).
@item int tm_year
This is the number of full calendar years since 1900.
@item int tm_wday
This is the number of full days since Sunday (in the range @code{0} through
@code{6}).
@item int tm_yday
This is the number of full days since the beginning of the year (in the
range @code{0} through @code{365}).
@item int tm_isdst
@cindex Daylight Saving Time
@cindex summer time
This is a flag that indicates whether Daylight Saving Time is (or was, or
will be) in effect at the time described. The value is positive if
Daylight Saving Time is in effect, zero if it is not, and negative if the
information is not available.
@item long int tm_gmtoff
This field describes the time zone that was used to compute this
broken-down time value, including any adjustment for daylight saving; it
is the number of seconds that you must add to UTC to get local time.
You can also think of this as the number of seconds east of UTC. For
example, for U.S. Eastern Standard Time, the value is @code{-5*60*60}.
The @code{tm_gmtoff} field is derived from BSD and is a GNU library
extension; it is not visible in a strict @w{ISO C} environment.
@item const char *tm_zone
This field is the name for the time zone that was used to compute this
broken-down time value. Like @code{tm_gmtoff}, this field is a BSD and
GNU extension, and is not visible in a strict @w{ISO C} environment.
@end table
@end deftp
@deftypefun {struct tm *} localtime (const time_t *@var{time})
@standards{ISO, time.h}
@safety{@prelim{}@mtunsafe{@mtasurace{:tmbuf} @mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
@c Calls tz_convert with a static buffer.
@c localtime @mtasurace:tmbuf @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c tz_convert dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
The @code{localtime} function converts the simple time pointed to by
@var{time} to broken-down time representation, expressed relative to the
user's specified time zone.
The return value is a pointer to a static broken-down time structure, which
might be overwritten by subsequent calls to @code{ctime}, @code{gmtime},
or @code{localtime}. (But no other library function overwrites the contents
of this object.)
The return value is the null pointer if @var{time} cannot be represented
as a broken-down time; typically this is because the year cannot fit into
an @code{int}.
Calling @code{localtime} also sets the current time zone as if
@code{tzset} were called. @xref{Time Zone Functions}.
@end deftypefun
Using the @code{localtime} function is a big problem in multi-threaded
programs. The result is returned in a static buffer and this is used in
all threads. POSIX.1c introduced a variant of this function.
@deftypefun {struct tm *} localtime_r (const time_t *@var{time}, struct tm *@var{resultp})
@standards{POSIX.1c, time.h}
@safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
@c localtime_r @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c tz_convert(use_localtime) @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c libc_lock_lock dup @asulock @aculock
@c tzset_internal @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c always called with tzset_lock held
@c sets static is_initialized before initialization;
@c reads and sets old_tz; sets tz_rules.
@c some of the issues only apply on the first call.
@c subsequent calls only trigger these when called by localtime;
@c otherwise, they're ok.
@c getenv dup @mtsenv
@c strcmp dup ok
@c strdup @ascuheap
@c tzfile_read @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c memcmp dup ok
@c strstr dup ok
@c getenv dup @mtsenv
@c asprintf dup @mtslocale @ascuheap @acsmem
@c stat64 dup ok
@c fopen dup @ascuheap @asulock @acsmem @acsfd @aculock
@c fileno dup ok
@c fstat64 dup ok
@c fclose dup @ascuheap @asulock @aculock @acsmem @acsfd
@c free dup @ascuheap @acsmem
@c fsetlocking dup ok [no @mtasurace:stream @asulock, exclusive]
@c fread_unlocked dup ok [no @mtasurace:stream @asucorrupt @acucorrupt]
@c memcpy dup ok
@c decode ok
@c bswap_32 dup ok
@c fseek dup ok [no @mtasurace:stream @asucorrupt @acucorrupt]
@c ftello dup ok [no @mtasurace:stream @asucorrupt @acucorrupt]
@c malloc dup @ascuheap @acsmem
@c decode64 ok
@c bswap_64 dup ok
@c getc_unlocked ok [no @mtasurace:stream @asucorrupt @acucorrupt]
@c tzstring dup @ascuheap @acsmem
@c compute_tzname_max dup ok [guarded by tzset_lock]
@c memset dup ok
@c update_vars ok [guarded by tzset_lock]
@c sets daylight, timezone, tzname and tzname_cur_max;
@c called only with tzset_lock held, unless tzset_parse_tz
@c (internal, but not static) gets called by users; given the its
@c double-underscore-prefixed name, this interface violation could
@c be regarded as undefined behavior.
@c strlen ok
@c tzset_parse_tz @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c sscanf dup @mtslocale @ascuheap @acsmem
@c isalnum dup @mtsenv
@c tzstring @ascuheap @acsmem
@c reads and changes tzstring_list without synchronization, but
@c only called with tzset_lock held (save for interface violations)
@c strlen dup ok
@c malloc dup @ascuheap @acsmem
@c strcpy dup ok
@c isdigit dup @mtslocale
@c compute_offset ok
@c tzfile_default @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c sets tzname, timezone, types, zone_names, rule_*off, etc; no guards
@c strlen dup ok
@c tzfile_read dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c mempcpy dup ok
@c compute_tzname_max ok [if guarded by tzset_lock]
@c iterates over zone_names; no guards
@c free dup @ascuheap @acsmem
@c strtoul dup @mtslocale
@c update_vars dup ok
@c tzfile_compute(use_localtime) @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c sets tzname; no guards. with !use_localtime, as in gmtime, it's ok
@c tzstring dup @acsuheap @acsmem
@c tzset_parse_tz dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c offtime dup ok
@c tz_compute dup ok
@c strcmp dup ok
@c offtime ok
@c isleap dup ok
@c tz_compute ok
@c compute_change ok
@c isleap ok
@c libc_lock_unlock dup @aculock
The @code{localtime_r} function works just like the @code{localtime}
function. It takes a pointer to a variable containing a simple time
and converts it to the broken-down time format.
But the result is not placed in a static buffer. Instead it is placed
in the object of type @code{struct tm} to which the parameter
@var{resultp} points.
If the conversion is successful the function returns a pointer to the
object the result was written into, i.e., it returns @var{resultp}.
@end deftypefun
@deftypefun {struct tm *} gmtime (const time_t *@var{time})
@standards{ISO, time.h}
@safety{@prelim{}@mtunsafe{@mtasurace{:tmbuf} @mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
@c gmtime @mtasurace:tmbuf @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c tz_convert dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
This function is similar to @code{localtime}, except that the broken-down
time is expressed as Coordinated Universal Time (UTC) (formerly called
Greenwich Mean Time (GMT)) rather than relative to a local time zone.
@end deftypefun
As for the @code{localtime} function we have the problem that the result
is placed in a static variable. POSIX.1c also provides a replacement for
@code{gmtime}.
@deftypefun {struct tm *} gmtime_r (const time_t *@var{time}, struct tm *@var{resultp})
@standards{POSIX.1c, time.h}
@safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
@c You'd think tz_convert could avoid some safety issues with
@c !use_localtime, but no such luck: tzset_internal will always bring
@c about all possible AS and AC problems when it's first called.
@c Calling any of localtime,gmtime_r once would run the initialization
@c and avoid the heap, mem and fd issues in gmtime* in subsequent calls,
@c but the unsafe locking would remain.
@c gmtime_r @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c tz_convert(gmtime_r) dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
This function is similar to @code{localtime_r}, except that it converts
just like @code{gmtime} the given time as Coordinated Universal Time.
If the conversion is successful the function returns a pointer to the
object the result was written into, i.e., it returns @var{resultp}.
@end deftypefun
@deftypefun time_t mktime (struct tm *@var{brokentime})
@standards{ISO, time.h}
@safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
@c mktime @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c passes a static localtime_offset to mktime_internal; it is read
@c once, used as an initial guess, and updated at the end, but not
@c used except as a guess for subsequent calls, so it should be safe.
@c Even though a compiler might delay the load and perform it multiple
@c times (bug 16346), there are at least two unconditional uses of the
@c auto variable in which the first load is stored, separated by a
@c call to an external function, and a conditional change of the
@c variable before the external call, so refraining from allocating a
@c local variable at the first load would be a very bad optimization.
@c tzset dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c mktime_internal(localtime_r) @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c ydhms_diff ok
@c ranged_convert(localtime_r) @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c *convert = localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c time_t_avg dup ok
@c guess_time_tm dup ok
@c ydhms_diff dup ok
@c time_t_add_ok ok
@c time_t_avg ok
@c isdst_differ ok
@c time_t_int_add_ok ok
The @code{mktime} function converts a broken-down time structure to a
simple time representation. It also normalizes the contents of the
broken-down time structure, and fills in some components based on the
values of the others.
The @code{mktime} function ignores the specified contents of the
@code{tm_wday}, @code{tm_yday}, @code{tm_gmtoff}, and @code{tm_zone}
members of the broken-down time
structure. It uses the values of the other components to determine the
calendar time; it's permissible for these components to have
unnormalized values outside their normal ranges. The last thing that
@code{mktime} does is adjust the components of the @var{brokentime}
structure, including the members that were initially ignored.
If the specified broken-down time cannot be represented as a simple time,
@code{mktime} returns a value of @code{(time_t)(-1)} and does not modify
the contents of @var{brokentime}.
Calling @code{mktime} also sets the current time zone as if
@code{tzset} were called; @code{mktime} uses this information instead
of @var{brokentime}'s initial @code{tm_gmtoff} and @code{tm_zone}
members. @xref{Time Zone Functions}.
@end deftypefun
@deftypefun time_t timelocal (struct tm *@var{brokentime})
@standards{???, time.h}
@safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
@c Alias to mktime.
@code{timelocal} is functionally identical to @code{mktime}, but more
mnemonically named. Note that it is the inverse of the @code{localtime}
function.
@strong{Portability note:} @code{mktime} is essentially universally
available. @code{timelocal} is rather rare.
@end deftypefun
@deftypefun time_t timegm (struct tm *@var{brokentime})
@standards{???, time.h}
@safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
@c timegm @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c gmtime_offset triggers the same caveats as localtime_offset in mktime.
@c although gmtime_r, as called by mktime, might save some issues,
@c tzset calls tzset_internal with always, which forces
@c reinitialization, so all issues may arise.
@c tzset dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
@c mktime_internal(gmtime_r) @asulock @aculock
@c ..gmtime_r @asulock @aculock
@c ... dup ok
@c tz_convert(!use_localtime) @asulock @aculock
@c ... dup @asulock @aculock
@c tzfile_compute(!use_localtime) ok
@code{timegm} is functionally identical to @code{mktime} except it
always takes the input values to be Coordinated Universal Time (UTC)
regardless of any local time zone setting.
Note that @code{timegm} is the inverse of @code{gmtime}.
@strong{Portability note:} @code{mktime} is essentially universally
available. @code{timegm} is rather rare. For the most portable
conversion from a UTC broken-down time to a simple time, set
the @code{TZ} environment variable to UTC, call @code{mktime}, then set
@code{TZ} back.
@end deftypefun
@node High Accuracy Clock
@subsection High Accuracy Clock
@cindex time, high precision
@cindex clock, high accuracy
@pindex sys/timex.h
@c On Linux, GNU libc implements ntp_gettime() and npt_adjtime() as calls
@c to adjtimex().
The @code{ntp_gettime} and @code{ntp_adjtime} functions provide an
interface to monitor and manipulate the system clock to maintain high
accuracy time. For example, you can fine tune the speed of the clock
or synchronize it with another time source.
A typical use of these functions is by a server implementing the Network
Time Protocol to synchronize the clocks of multiple systems and high
precision clocks.
These functions are declared in @file{sys/timex.h}.
@tindex struct ntptimeval
@deftp {Data Type} {struct ntptimeval}
This structure is used for information about the system clock. It
contains the following members:
@table @code
@item struct timeval time
This is the current calendar time, expressed as the elapsed time since
the epoch. The @code{struct timeval} data type is described in
@ref{Elapsed Time}.
@item long int maxerror
This is the maximum error, measured in microseconds. Unless updated
via @code{ntp_adjtime} periodically, this value will reach some
platform-specific maximum value.
@item long int esterror
This is the estimated error, measured in microseconds. This value can
be set by @code{ntp_adjtime} to indicate the estimated offset of the
system clock from the true calendar time.
@end table
@end deftp
@deftypefun int ntp_gettime (struct ntptimeval *@var{tptr})
@standards{GNU, sys/timex.h}
@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
@c Wrapper for adjtimex.
The @code{ntp_gettime} function sets the structure pointed to by
@var{tptr} to current values. The elements of the structure afterwards
contain the values the timer implementation in the kernel assumes. They
might or might not be correct. If they are not, an @code{ntp_adjtime}
call is necessary.
The return value is @code{0} on success and other values on failure. The
following @code{errno} error conditions are defined for this function:
@vtable @code
@item TIME_ERROR
The precision clock model is not properly set up at the moment, thus the
clock must be considered unsynchronized, and the values should be
treated with care.
@end vtable
@end deftypefun