📄 time.texi
字号:
@node Date and Time, Non-Local Exits, Arithmetic, Top@chapter Date and TimeThis chapter describes functions for manipulating dates and times,including functions for determining what the current time is andconversion between different time representations.The time functions fall into three main categories:@itemize @bullet@item Functions for measuring elapsed CPU time are discussed in @ref{ProcessorTime}.@itemFunctions for measuring absolute clock or calendar time are discussed in@ref{Calendar Time}.@itemFunctions for setting alarms and timers are discussed in @ref{Settingan Alarm}.@end itemize@menu* Processor Time:: Measures processor time used by a program.* 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.* Resource Usage:: Measuring various resources used.* Limits on Resources:: Specifying limits on resource usage.* Priority:: Reading or setting process run priority.@end menu@node Processor Time@section Processor TimeIf you're trying to optimize your program or measure its efficiency, it'svery useful to be able to know how much @dfn{processor time} or @dfn{CPUtime} it has used at any given point. Processor time is different fromactual wall clock time because it doesn't include any time spent waitingfor I/O or when some other process is running. Processor time isrepresented by the data type @code{clock_t}, and is given as a number of@dfn{clock ticks} relative to an arbitrary base time marking the beginningof a single program invocation.@cindex CPU time@cindex processor time@cindex clock ticks@cindex ticks, clock@cindex time, elapsed CPU@menu* Basic CPU Time:: The @code{clock} function.* Detailed CPU Time:: The @code{times} function.@end menu@node Basic CPU Time@subsection Basic CPU Time InquiryTo get the elapsed CPU time used by a process, you can use the@code{clock} function. This facility is declared in the header file@file{time.h}.@pindex time.hIn typical usage, you call the @code{clock} function at the beginning andend of the interval you want to time, subtract the values, and then divideby @code{CLOCKS_PER_SEC} (the number of clock ticks per second), like this:@smallexample@group#include <time.h>clock_t start, end;double elapsed;start = clock();@dots{} /* @r{Do the work.} */end = clock();elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;@end group@end smallexampleDifferent computers and operating systems vary wildly in how they keeptrack of processor time. It's common for the internal processor clockto have a resolution somewhere between hundredths and millionths of asecond.In the GNU system, @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 type of the macro @code{CLOCKS_PER_SEC} can beeither integer or floating-point types. Casting processor time valuesto @code{double}, as in the example above, makes sure that operationssuch as arithmetic and printing work properly and consistently no matterwhat the underlying representation is.@comment time.h@comment ANSI@deftypevr Macro int CLOCKS_PER_SECThe value of this macro is the number of clock ticks per second measuredby the @code{clock} function.@end deftypevr@comment time.h@comment POSIX.1@deftypevr Macro int CLK_TCKThis is an obsolete name for @code{CLOCKS_PER_SEC}. @end deftypevr@comment time.h@comment ANSI@deftp {Data Type} clock_tThis is the type of the value returned by the @code{clock} function.Values of type @code{clock_t} are in units of clock ticks.@end deftp@comment time.h@comment ANSI@deftypefun clock_t clock (void)This function returns the elapsed processor time. The base time isarbitrary but doesn't change within a single process. If the processortime is not available or cannot be represented, @code{clock} returns thevalue @code{(clock_t)(-1)}.@end deftypefun@node Detailed CPU Time@subsection Detailed Elapsed CPU Time InquiryThe @code{times} function returns more detailed information aboutelapsed processor time in a @w{@code{struct tms}} object. You shouldinclude the header file @file{sys/times.h} to use this facility.@pindex sys/times.h@comment sys/times.h@comment POSIX.1@deftp {Data Type} {struct tms}The @code{tms} structure is used to return information about processtimes. It contains at least the following members:@table @code@item clock_t tms_utimeThis is the CPU time used in executing the instructions of the callingprocess.@item clock_t tms_stimeThis is the CPU time used by the system on behalf of the calling process.@item clock_t tms_cutimeThis is the sum of the @code{tms_utime} values and the @code{tms_cutime}values of all terminated child processes of the calling process, whosestatus has been reported to the parent process by @code{wait} or@code{waitpid}; see @ref{Process Completion}. In other words, itrepresents the total CPU time used in executing the instructions of allthe terminated child processes of the calling process, excluding childprocesses which have not yet been reported by @code{wait} or@code{waitpid}.@item clock_t tms_cstimeThis is similar to @code{tms_cutime}, but represents the total CPU timeused by the system on behalf of all the terminated child processes of thecalling process.@end tableAll of the times are given in clock ticks. These are absolute values; in anewly created process, they are all zero. @xref{Creating a Process}.@end deftp@comment sys/times.h@comment POSIX.1@deftypefun clock_t times (struct tms *@var{buffer})The @code{times} function stores the processor time information forthe calling process in @var{buffer}.The return value is the same as the value of @code{clock()}: the elapsedreal time relative to an arbitrary base. The base is a constant within aparticular process, and typically represents the time since systemstart-up. A value of @code{(clock_t)(-1)} is returned to indicate failure.@end deftypefun@strong{Portability Note:} The @code{clock} function described in@ref{Basic CPU Time}, is specified by the ANSI C standard. The@code{times} function is a feature of POSIX.1. In the GNU system, thevalue returned by the @code{clock} function is equivalent to the sum ofthe @code{tms_utime} and @code{tms_stime} fields returned by@code{times}.@node Calendar Time@section Calendar TimeThis section describes facilities for keeping track of dates and timesaccording to the Gregorian calendar.@cindex Gregorian calendar@cindex time, calendar@cindex date and timeThere are three representations for date and time information:@itemize @bullet@item @dfn{Calendar time} (the @code{time_t} data type) is a compact representation, typically giving the number of seconds elapsed sincesome implementation-specific base time.@cindex calendar time@itemThere is also a @dfn{high-resolution time} representation (the @code{structtimeval} data type) that includes fractions of a second. Use this timerepresentation instead of ordinary calendar time when you need greaterprecision.@cindex high-resolution time@item@dfn{Local time} or @dfn{broken-down time} (the @code{structtm} data type) represents the date and time as a set of componentsspecifying the year, month, and so on, for a specific time zone.This time representation is usually used in conjunction with formattingdate and time values.@cindex local time@cindex broken-down time@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.* Formatting Date and Time:: Converting times to strings.* 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 TimeThis section describes the @code{time_t} data type for representingcalendar time, and the functions which operate on calendar time objects.These facilities are declared in the header file @file{time.h}.@pindex time.h@cindex epoch@comment time.h@comment ANSI@deftp {Data Type} time_tThis is the data type used to represent calendar time. In the GNU Clibrary and other POSIX-compliant implementations, @code{time_t} isequivalent to @code{long int}. When interpreted as an absolute timevalue, it represents the number of seconds elapsed since 00:00:00 onJanuary 1, 1970, Coordinated Universal Time. (This date is sometimesreferred to as the @dfn{epoch}.)In other systems, @code{time_t} might be either an integer orfloating-point type.@end deftp@comment time.h@comment ANSI@deftypefun double difftime (time_t @var{time1}, time_t @var{time0})The @code{difftime} function returns the number of seconds elapsedbetween time @var{time1} and time @var{time0}, as a value of type@code{double}. In the GNU system, you can simply subtract @code{time_t} values. But onother systems, the @code{time_t} data type might use some other encodingwhere subtraction doesn't work directly.@end deftypefun@comment time.h@comment ANSI@deftypefun time_t time (time_t *@var{result})The @code{time} function returns the current time as a value of type@code{time_t}. If the argument @var{result} is not a null pointer, thetime value is also stored in @code{*@var{result}}. If the calendar time is not available, the value @code{(time_t)(-1)} is returned.@end deftypefun@node High-Resolution Calendar@subsection High-Resolution CalendarThe @code{time_t} data type used to represent calendar times has a resolution of only one second. Some applications need more precision.So, the GNU C library also contains functions which are capable ofrepresenting calendar times to a higher resolution than one second. Thefunctions and the associated data types described in this section aredeclared in @file{sys/time.h}.@pindex sys/time.h@comment sys/time.h@comment BSD@deftp {Data Type} {struct timeval}The @code{struct timeval} structure represents a calendar time. Ithas the following members:@table @code@item long int tv_secThis represents the number of seconds since the epoch. It is equivalentto a normal @code{time_t} value.@item long int tv_usecThis is the fractional second value, represented as the number ofmicroseconds.Some times struct timeval values are used for time intervals. Then the@code{tv_sec} member is the number of seconds in the interval, and@code{tv_usec} is the number of additional microseconds.@end table@end deftp@comment sys/time.h@comment BSD@deftp {Data Type} {struct timezone}The @code{struct timezone} structure is used to hold minimal informationabout the local time zone. It has the following members:@table @code@item int tz_minuteswestThis is the number of minutes west of GMT.@item int tz_dsttimeIf nonzero, daylight savings time applies during some part of the year.@end tableThe @code{struct timezone} type is obsolete and should never be used.Instead, use the facilities described in @ref{Time Zone Functions}.@end deftpIt is often necessary to subtract two values of type @w{@code{structtimeval}}. Here is the best way to do this. It works even on somepeculiar operating systems where the @code{tv_sec} member has anunsigned type.@smallexample/* @r{Subtract the `struct timeval' values X and Y,} @r{storing the result in RESULT.} @r{Return 1 if the difference is negative, otherwise 0.} */inttimeval_subtract (result, x, y) struct timeval *result, *x, *y;@{ /* @r{Perform the carry for the later subtraction by updating @var{y}.} */ if (x->tv_usec < y->tv_usec) @{ int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; @} if (x->tv_usec - y->tv_usec > 1000000) @{ int nsec = (y->tv_usec - x->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; @} /* @r{Compute the time remaining to wait.} @r{@code{tv_usec} is certainly positive.} */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* @r{Return 1 if result is negative.} */ return x->tv_sec < y->tv_sec;@}@end smallexample@comment sys/time.h@comment BSD@deftypefun int gettimeofday (struct timeval *@var{tp}, struct timezone *@var{tzp})The @code{gettimeofday} function returns the current date and time in the@code{struct timeval} structure indicated by @var{tp}. Information about thetime zone is returned in the structure pointed at @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. Thefollowing @code{errno} error condition is defined for this function:@table @code@item ENOSYSThe operating system does not support getting time zone information, and@var{tzp} is not a null pointer. The GNU operating system does notsupport using @w{@code{struct timezone}} to represent time zoneinformation; that is an obsolete feature of 4.3 BSD.Instead, use the facilities described in @ref{Time Zone Functions}.@end table@end deftypefun@comment sys/time.h@comment BSD@deftypefun int settimeofday (const struct timeval *@var{tp}, const struct timezone *@var{tzp})The @code{settimeofday} function sets the current date and timeaccording to the arguments. As for @code{gettimeofday}, time zoneinformation is ignored if @var{tzp} is a null pointer.You must be a privileged user in order to use @code{settimeofday}.The return value is @code{0} on success and @code{-1} on failure. The
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -