Make a little progress every day __linux of time processing in--linux system

Source: Internet
Author: User
Tags time zones local time


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






In the process of time processing is often a problem, the Linux system provides a lot of time processing functions, we can use these functions to complete the functions we need. What are some of the time issues that are usually concerned with the program? Real time: The time that the program runs, that is, the time that the program starts to die or the time that the program runs through, the amount of CPU time used by a process, which is suitable for checking or optimizing the program and algorithm performance. This article focuses on the processing and conversion of real time.
first,Epoch

Regardless of geographical location, Linux system internal time representation is measured by the number of seconds since Epoch, Epoch is Universal Coordinated Time (UTC, formerly known as Greenwich Mean Time, or GMT) January 1, 1970 Horizon 0 minutes and 0 seconds. This is roughly the time the UNIX system came out. The time can be stored in a variable of type time_t. In a 32-bit Linux system, time_t is a signed integer that can be expressed as a date range from December 13, 1901 20:45 52 seconds to January 19, 2038 03:14:07. Therefore, 32-bit system machines will face 2038 years of problems, of course, we do not have to worry, in 2038 years, I believe that these systems have been upgraded to 64-bit or more bits of the system. However, some of the more long-lived embedded devices may be affected by this problem.
second, the time conversion function 

as shown in the following figure, the values stored in the time_t variable can be converted to and from other time formats, which also contains the printout. These functions mask the complexity of transformations caused by issues such as time zones, daylight savings Period (DST), and localization





Third, function detailed

1. System call Gettimeofday (), which is used to return the calendar time in the buffer that the TV points to, and its declaration is as follows #include <sys/time.h>
Return 0 in success, or-1 on error int gettimeofday (struct timeval* TV, struct timezone*);
The structure that the TV points to is as follows struct Timeval {time_t tv_sec;        /* Seconds since 00:00:00, 1 1970 utc*/susecond_t; /* Additional microseconds (long int) */}; The Gettimeofday () function provides precision at microsecond level and is stored in tv_usec, which is already satisfied for most programs. On the x86-64 platform, Gettimeofday () is not a system call, but is implemented in user state, without context switching and the overhead of getting stuck in the kernel, so its speed is relatively fast [1]. The parameter tz is a historical product that was used in an earlier UNIX system implementation to obtain the system's time zone information, which is now deprecated and therefore always set to null at call time.
2. System call time (), which returns the number of seconds since epoch, is declared as follows #include <time.h>
Returns number of seconds since the Epoch, or (time_t)-1 On Error time_t time (time_t* TIMEP);
If the TIMEP parameter is not NULL, the number of seconds since epoch is also placed in the position that TIMEP points to. But in everyday use we all adopt a simple invocation method of T = Time (NULL). You can tell from the function description that the accuracy of gettimeofday () is higher than time ().
3. time_t can be used to store epoch to the current number of seconds, which is very inconvenient for us to explain directly, because we are more receptive to the form of Mm-dd-yy HH:MIN:SS. Linux provides a simple CTime () function to handle time_t conversion #include <time.h>
Returns pointer to statically allocated string terminated by newline and-on success, or NULL On Error char* CTime (c Onst time_t* TIMEP);
Passing a pointer to time_t as the TIMEP parameter passes in a string of up to 26 bytes, containing the date and time of the standard format, as follows: Wed May 14 15:22:34 2014 The string contains a newline conforming to the terminating null byte. The CTime () function automatically considers the local time zone and DST settings when making row conversions. The returned string is statically allocated so there is no need to invoke the free function, which is why the function is not reentrant (not 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) (0)/int tm_isdst; /*daylight saving Time flag > 0:DST are in effect; = 0:DST is not effect; < 0:DST information not available*/
}; The structure TM breaks down the date and time into separate fields, which makes it easier for the program to get different field values to handle. The upper limit for field tm_sec is 60 instead of 59, which is designed primarily to consider leap seconds, occasionally adapting the human calendar to the precise astronomical year (the so-called regression year). If a _BSD_SOURCE test macro is defined in the program, the GLIBC-defined TM structure will also include two fields, a long int tm_gmtoff, which represents the number of seconds beyond UTC, one for const char* Tm_zone, An abbreviation for the time zone (for example, CEST is a central European daylight saving room).
The Gmtime () and localtime () two functions convert time_t to struct TM. Gmtime () the Tm,localtime () that Decomposes time_t into UTC time needs to take into account the time zone and daylight saving period settings, as follows: #include <time.h>
Both return a pointer to a statically allocated broker-down time structure in success, or NULL on error struct tm* Me (const time_t *TIMEP); struct tm* localtime (const time_t *TIMEP); All two of these functions are not thread safe, and the thread-safe version is Gmtime_r () and Localtime_r ()
The Mktime () function converts struct TM to time_t, which is declared as follows: #include <time.h>
Returns seconds since the Epoch corresponding to timeptr on success, or (time_t)-1 On Error time_t mktime (struct TM *t IMEPTR); The function may modify the value of the timeptr, at least ensuring that the Tm_wday and Tm_yday fields are set up to ensure that the fields correspond to the other fields. Also, Mktime () sets the time zone when the conversion occurs. In addition, the use of DST settings depends on the value of the input field tm_isdst. If the TM_ISDST is 0, this is considered a standard time (that is, ignoring daylight savings) if the TM_ISDST is greater than 0, this is considered daylight saving time if TM_ISDST is less than 0, an attempt is made to determine whether DST will take effect at this hour of the year. This is often the ideal setting for 5. Convert struct TM to easy to understand string #include <time.h>
Returns pointer to statically allocated a string terminated by newline and "on success, or NULL On error char* asctime (const struct TM *timeptr);
The settings for the local time zone have no effect on asctime () compared to CTime (). The pointer returned by it points to a statically allocated string, so it is not thread safe, the thread-safe version is Asctime_r (), and the output is probably as follows: Wed May 16:43:21 CET 2014
The Asctime () function returns a fixed form of string, sometimes in order to be easier to understand, the program does not want to limit itself to such a string, so Linux provides the strftime () function, declared as follows: #include <time.h>
Returns number of bytes placed in outstr (excluding terminating null bytes) on success, or 0 On error size_t strftime ( Char *outstr, size_t maxsize, const char *format, const struct TM *timeptr);
The string returned in OUTSTR is formatted according to the format defined by the format parameter, maxsize is the maximum length of the ourstr and, if successful, writes the formatted content to the buffer to which the outstr points, and then returns the true length of the string, including terminating the null byte, If the true length exceeds the size of the MAXSIZE parameter, then 0 is returned to indicate an error and the contents of the OUTSTR cannot be determined. The parameter format is a string, similar to the printf () parameter. Specific values do not do this in detail, you can Google.
The Strptime () function, in contrast to the strftime () function, converts a string containing a date and time into a struct TM, declared as follows: #define _xopen_source #include <time.h>
Returns Pointer to next unprocessed character into Str on success, or NULL On Error char* strptime (const char *STR, cons t char *format, struct TM *timeptr);
The function strptime () resolves the string str, which consists of date and time, according to the format parameter content, and stores the converted value in the cache referred to in timeptr, and if successful, returns the next character in Str that has not been resolved. If the given STR cannot correspond to the format, it resolves the failure and returns null as an error. Finally, note that the Strptime () function does not set the TM_ISDST field in the TM.
Fourth, time zone

Different countries use different time zones and daylight savings, and the time zone must be considered for programs that want to enter output times, especially distributed systems around the world. Due to too much time zone information, Linux systems do not encode them directly into a program or function library, but are stored in a standard format in a file. These files are located in the/usr/share/zoneinfo directory. The system's local time zone is defined by the file/etc/localtime, which is usually a file linked to/usr/share/zoneinfo. The time zone file format is narrated on the Tzfile (5) man page, which can be created by Zic (8) (Time zone information compiler, zone information compiler) tool. The Zdump (8) command specifies a time zone for the program to run based on the time zone in the specified time zone file, and the TZ environment variable is set to a colon (:) and time zone name, where the time zone name is defined in/usr/share/zoneinfo.     The time zone settings affect functions such as CTime (), localtime (), Mktime (), strftime (), and in order to get the time zone settings, these functions invoke Tzset (3) to set the following global variables: char *tzname[2];            /*name of TimeZone and alternate (DST) timezone*/int daylight;       /*nonzero If there is a alternate (DST) timezone*/long timezone; /*seconds difference between UTC and local standard time*/
Fifth. Summary

Multiple system calls allow us to acquire and set the time of the system, and a series of library functions enables us to perform conversions between various time representations. Linux is a non-real-time multitasking operating system, and if we want to do it in a program that's completely accurate timing and timing, because the current task may be switched by the CPU at any time, these functions are sufficient to meet the needs of the day-to-day processing. This article does not cover the described function use cases, such as the use of these functions in the program, you can Baidu or Google, and then you can view the https://github.com/ApusApp/Swift/tree/master/swift/base in the implementation of time processing.

Related Article

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.