A little progress every day-time processing in Linux

Source: Internet
Author: User
Tags time zones

Reprint please explain the source: http://blog.csdn.net/cywosp/article/details/25839551


In a program, time processing is often a troublesome task. Linux provides a lot of time processing functions. We can use these functions to complete the functions we need. So what time issues will be concerned in the program?
  • Real time: the time when the program runs, that is, the time when the program starts to die or the time when the program runs until now
  • Process time: the total CPU time used by a process. It is suitable for checking or optimizing the performance of programs and algorithms.
This article only focuses on the processing and conversion of Real Time
I. EpochRegardless of the geographical location, the time representation in Linux is measured in seconds since Epoch. Epoch is the Universal Coordinated Time (UTC, also known as Greenwich Mean Time, or GMT) January 1, 1970 00:00:00. This is roughly the time when UNIX systems came into existence. This time can be stored in time_t type variables.
In a 32-bit Linux system, time_t is a signed integer, which indicates that the date range is from 03:14:07, January 1, December 13, 1901 to, January 1, January 19, 2038. Therefore, 32-bit systems will all face problems in 2038. Of course, we don't have to worry about this. By 2038, I believe these systems have already been upgraded to 64-bit or more systems. However, some embedded devices with longer lifetime may be affected by this problem.

Ii. Time conversion functionsAs shown in, the values stored in the time_t variable can be converted to other time formats, including printed output. These functions shield the transformation from various complexities caused by problems such as time zone, Daylight Saving Time (DST), and localization.

Iii. Function details1. The system calls gettimeofday () to return the calendar time in the buffer to which TV points. Its declaration is as follows:
# Include <sys/time. h>
// Return 0 on success, or-1 on errorint gettimeofday (struct timeval * TV, struct timezone * tz );
The struct pointed to by TV is struct timeval {time_t TV _sec;/* Seconds since 00:00:00, 1 Jan 1970 UTC */susecond_t TV _usec;/* Additional microseconds (long int )*/}; the gettimeofday () function provides microsecond-level precision and stores it in TV _usec. This accuracy is sufficient for most programs. On the x86-64 platform, gettimeofday () is not a system call, but is implemented in the user State, without context switching and falling into the kernel overhead, so its speed is relatively fast [1]. The parameter tz Is a historical product. It was used in earlier UNIX system implementations to obtain the system's time zone information. It has been deprecated, so it is always set to NULL during the call.

2. The system calls time () and returns the number of seconds since Epoch. The declaration is as follows:
# Include <time. h>
// Returns number of seconds since the Epoch, or (time_t)-1 on errortime_t time (time_t * timep );
If the timep parameter is not NULL, the number of seconds since Epoch is placed in the position pointed to by timep. However, in daily use, we use the simple call method t = time (NULL ). The function description shows that the accuracy of gettimeofday () is higher than that of time.

3. time_t can be used to store Epoch to the current number of seconds, which is very difficult for us to explain directly, because we are more likely to accept the form of MM-DD-YY HH: MIN: SS. Linux provides a simple ctime () function to process time_t conversion.
# Include <time. h>
// Returns pointer to statically allocated string terminated by newline and \ 0 on success, or NULL on errorchar * ctime (const time_t * timep );
Passing a pointer to time_t as the timep parameter to the function will return a string of up to 26 bytes, containing the date and time in the standard format, as shown below: wed May 14 15:22:34 2014 this string contains a line break that matches each ending NULL byte. The ctime () function automatically considers the local time zone and DST settings when converting the data in the row. The returned string is statically allocated, so you do not need to call the free function. Therefore, this function cannot be reentrant (non-thread-safe), and the thread-safe version is ctime_r ().

4. Conversion between time_t and struct tm
Struct tm {int tm_sec;/* Seconds (0-60) */int tm_min;/* Minites (0-59) */int tm_hour;/* Hours (0-23) */int tm_mday;/* Day of the month (1-31) */int tm_mon;/* Month (1-12) */int tm_year; /* Year since 1900 */int tm_wday;/* Day of the week (Sunday = 0) */int tm_yday;/* Day in the year (0-365; 1 Jan = 0) */int tm_isdst;/* Daylight saving time flag> 0: DST is in effect; = 0: DST is not effect; <0: DST information not available */
}; Struct tm splits the date and time into multiple independent fields, so that the program can obtain different field values for processing. The maximum value of the field tm_sec is 60 rather than 59. This design mainly considers the leap second and occasionally uses it to adjust the human calendar to the precise astronomical year (so-called return year ). If the _ BSD_SOURCE test macro is defined in the program, the tm structure defined by glibc also contains two fields, one being long int tm_gmtoff, which indicates the number of seconds beyond UTC, the name is const char * tm_zone, which is used to represent the abbreviation of the time zone (for example, CEST is the summer time of Central Europe ).
The gmtime () and localtime () functions can convert time_t to struct tm. Gmtime () directly splits time_t into the tm of UTC time. localtime () needs to consider the settings of the time zone and runtime. The specific declaration is as follows: # include <time. h>
// Both return a pointer to a statically allocated broker-down time structure on success, or NULL on errorstruct tm * gmtime (const time_t * timep ); struct tm * localtime (const time_t * timep); both of the preceding functions are non-thread-safe. The thread-safe versions are gmtime_r () and localtime_r ()
The mktime () function can convert struct tm to time_t. Its declaration is as follows: # include <time. h>
// Returns seconds since the Epoch corresponding to timeptr on success, or (time_t)-1 on errortime_t mktime (struct tm * timeptr); this function may modify the value of timeptr, at least make sure that the tm_wday and tm_yday fields are set to ensure that these fields can correspond to other fields. At the same time, mktime () sets the time zone during conversion. In addition, the use of DST settings depends on the value of the input field tm_isdst.
  • If tm_isdst is 0, this time is treated as the standard time (that is, ignore the timeout)
  • If tm_isdst is greater than 0, this time is considered as the timeout time.
  • If tm_isdst is less than 0, try to determine whether DST takes effect at this time of the year. This is often the setting that everyone expects.
5. Convert struct tm into a string that is easy to understand
# Include <time. h>
// Returns pointer to statically allocated string terminated by newline and \ 0 on success, or NULL on errorchar * asctime (const struct tm * timeptr );
Compared with ctime (), the local time zone setting has no effect on asctime. The returned Pointer Points to a statically allocated string, so it is not thread-safe. The thread-safe version is asctime_r (). The output result is roughly as follows: Wed May 14 16:43:21 CET 2014
The asctime () function returns a fixed string. Sometimes, to make it easier to understand, the program does not want to be limited to such a string. Therefore, the strftime () function is provided in Linux. The declaration is as follows: # include <time. h>
// Returns number of bytes placed in outstr (excluding terminating null bytes) on success, or 0 on errorsize_t strftime (char * outstr, size_t maxsize, const char * format, const struct tm * timeptr );
The string returned by outstr is formatted according to the format defined by the format parameter. maxsize is the maximum length of ourstr. If it is successful, the formatted content is written to the buffer zone pointed to by outstr, then return the true length of the string, including the ending Null Byte. If the actual length exceeds the size of the maxsize parameter, return 0 to indicate an error and the content of outstr cannot be determined. The format parameter is a string, similar to the printf () parameter. The specific values are not described here. You can use google.
The strptime () function is the opposite of the strftime () function. It can convert strings containing dates and times to struct tm. The declaration is as follows: # define _ XOPEN_SOURCE # include <time. h>
// Returns pointer to next unprocessed character in str on success, or NULL on errorchar * strptime (const char * str, const char * format, struct tm * timeptr );
The strptime () function parses the str string consisting of date and time according to the format parameter content, and stores the converted value in the cache referred to by timeptr. If the conversion succeeds, returns the next character in str that has not been parsed. If the given str cannot match the format, the parsing fails and NULL is returned to indicate an error. Note that the strptime () function does not set the tm_isdst field in tm.

Iv. Time ZoneDifferent countries use different time zones and daylight saving time. For programs that want to input and output time, you must consider the time zone, especially the Global distributed system. Due to too much time zone information, the Linux system does not directly encode it in a program or function library, but stores it in a standard format. These files are located in the/usr/share/zoneinfo directory. The local time zone of the system is defined by the file/etc/localtime, which is usually a file linked to/usr/share/zoneinfo.
The Time zone file format is recorded on the tzfile (5) manual page. It can be created using the zic (8) (Time zone information compiler, zone information compiler) tool. The zdump (8) command displays the current time based on the time zone in the specified time zone file.
To specify a time zone for a running program, you must set the TZ environment variable to a string consisting of a colon (:) and a time zone name. The time zone name is defined in/usr/share/zoneinfo. The Time Zone settings affect functions such as ctime (), localtime (), mktime (), and strftime (). To obtain the time zone settings, these functions call tzset (3) set the following global variables:
Char * tzname [2];/* Name of timezone and alternate (DST) timezone */int daylight;/* Nonzero if there is an alternate (DST) timezone */long timezone; /* Seconds difference between UTC and local standard time */

V. SummaryMultiple system calls allow us to get and set the system time, and a series of library functions allow us to complete the conversion between various time representations. Linux is a non-real-time multi-task operating system. If we want to completely precise timing and timing in the program, the current task may be switched out by the CPU at any time, however, in daily time processing, the above functions are sufficient to meet the requirements. This article does not cover the function cases mentioned. If you use these functions in a program, you can use them either Baidu or google. For more information, see https://github.com/apusapp/swift/tree/master/swift/base#real-time processing.

Refer to [1] http://lwn.net/Articles/446528

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.