Structure and related functions representing "Time" in Linux

Source: Internet
Author: User
Tags posix

Reproduced in: http://blog.chinaunix.net/uid-25909722-id-2827364.html architecture and related functions representing "Time" in Linux 2011-09-13 17:01:13

Category: C/

In the Linux system, there are many structures representing the concept of "time", and there are a lot of related time-processing functions, which gives people a very confusing feeling. Cause when we really want to use these structures and functions, we do not know exactly which structure and which functions to use. It is necessary to summarize. By looking up documents/usr/include/time.h and/usr/include/bits/time.h (1)We can find the following four types of representations structure of "time"
  1. /* Returned by ' time '. */
  2. typedef __time_t time_t;
  3. /* A time value that's accurate to the nearest
  4. Microsecond but also have a range of years. */
  5. struct Timeval
  6. {
  7. __time_t tv_sec; /* Seconds. */
  8. __suseconds_t tv_usec; /* microseconds. */
  9. };
  10. struct TIMESPEC
  11. {
  12. __time_t tv_sec; /* Seconds. */
  13. long int tv_nsec; /* nanoseconds. */
  14. };
  15. struct TM
  16. {
  17. int tm_sec;    /* Seconds. [0-60] (1 leap second) */
  18. int tm_min;    /* Minutes. [0-59] */
  19. int tm_hour;    /* Hours. [0-23] */
  20. int tm_mday;        /* Day. [1-31] */
  21. int Tm_mon;    /* Month. [0-11] */
  22. int tm_year; /* Year-1900. */
  23. int tm_wday;    /* Day of week. [0-6] */
  24. int tm_yday; /* days in year. [0-365] */
  25. int tm_isdst;        /* DST. [ -1/0/1]*/
  26. #ifdef __USE_BSD
  27. long int tm_gmtoff; /* Seconds east of UTC. */
  28. __const Char *tm_zone; /* Timezone abbreviation. */
  29. #else
  30. long int __tm_gmtoff; /* Seconds east of UTC. */
  31. __const Char *__tm_zone; /* Timezone abbreviation. */
  32. #endif
  33. };
whichtime_t is a long integer used to represent the number of seconds. struct Timeval structures are expressed in seconds and subtleties of time. the struct timespec struct represents time in seconds and nanoseconds. The struct TM represents time directly in seconds, minutes, hours, days, months, years, and so on. It is clear that their accuracy is different. A variety of different needs to provide a variety of different options. (2)In a Linux system, how do we gets the current time? #include time_t Time (time_t *t);You can get the number of seconds that are accurate to the current distance 1970-01-01 00:00:00 +0000 (UTC). #include int gettimeofday (struct timeval *tv, struct timezone *tz);You can obtain a microsecond number that is accurate to the current distance of 1970-01-01 00:00:00 +0000 (UTC). #include int Clock_gettime (clockid_t clk_id, struct timespec *tp);You can get the number of nanoseconds that are accurate to nanosecond current distance 1970-01-01 00:00:00 +0000 (UTC). Example:
    1. #include <time.h>
    2. #include <stdio.h>
    3. int main ()
    4. {
    5. struct TIMESPEC ts;
    6. Clock_gettime (Clock_realtime, &ts);
    7. printf ("%.24s%ld nanoseconds\n", CTime (&ts.tv_sec), ts.tv_nsec);
    8. return 0;
    9. }
Compile: Gcc-wall-lrt-o mytime time.c (note to join link options-LRT) Run:./mytime results: Tue Sep 18:04:44 740953975 nanosecondsSummary: We can get the current time of three different precision through the above three functions. Note:posix.1-2008 marks Gettimeofday () as obsolete, recommending the use of clock_gettime (2) instead.and, someone has done a test, two consecutive times using Gettimeofday, will be a small probability of "time back" phenomenon, the second function call to get less than or say earlier than the first tuneUsed to get the time. The Gettimeofday function is not so stable, no times or clock timing is accurate, but they are similar in usage. Clock has a time limit, said to be 596.5+ hours, the general situation is sufficient to cope. "(Excerpt from Online)"processes such as ntpd may modify system time, resulting in timing errors。 According to the discussion on the Internet,TSC and Hpet interrupt things that could cause the system to wall time fallback。 This should be related to the specific system implementation, in short, the Gettimeofday function does not guarantee the accuracy of the provided, nor guarantee the accurate time of the system,it returns the result "the system's best guess at wall time""(excerpt from online) if possible, try to use Clock_gettime (clock_monotonic), but not all systems implement POSIX realtime, such as Mac OS X" (excerpt from the web) and should now be used:int Clock_gettime (clock_monotonic, struct timespec *tp); clock_monotonic: CLOCK that cannot be set and represents monotonic time since some UNSPECIF IED starting point. (3)Conversion between seconds, milliseconds, microseconds, nanoseconds 1 seconds = = 1000 msec 1 msec = 1000 microseconds 1 microseconds = 1000 nanoseconds so:1 seconds = 1000,000 microseconds (1 million microseconds) 1 seconds = 1000,000,000 nanoseconds (1 billion nanoseconds) from seconds to milliseconds, milliseconds to microseconds, microseconds to nanoseconds are 1000 times as many as 3 0 relationships. another: The microprocessor of a personal computer executes a directive (such as adding two numbers) to approximately 2 to 4 nanoseconds. So the program just has to be accurate to nanosecond enough.   (4)How do we do the time Formatting and outputIt?
    1. #include <time.h>
    2. Char *asctime (const struct TM *TM);
    3. Char *asctime_r (const struct TM *tm, char *buf);
    4. Char *ctime (const time_t *TIMEP);
    5. Char *ctime_r (const time_t *TIMEP, char *buf);
    6. sizt_t strftime (char *s, size_t max, const char *format, const struct TM *TM);
Obviously, to strictly control the output format of the time, you can only use the Strftime function, but the function can only be used to output the time that the struct TM represents, so it is related to struct timeval, struct timespec, time_ How the time represented by T is converted into a struct TM form. In addition, because the STRUTC TM can only be accurate to the second, I milliseconds, microseconds, nanoseconds can only be output separately. So, the way we take it is: FirstConvert the struct timeval, struct timespec etc into the number of seconds represented by time_t;
    1. struct Timeval TV;
    2. struct TIMESPEC ts;
    3. time_t SEC_TV = tv.tv_sec;
    4. time_t sec_ts = ts.ts_sec;
thenConvert time_t into a struct TM using the following functions
    1. struct TM *gmtime (const time_t *TIMEP);
    2. struct TM *gmtime_r (const time_t *TIMEP, struct TM *result);
    3. Or:
    4. struct TM *localtime (const time_t *TIMEP);
    5. struct TM *localtime_r (const time_t *TIMEP, struct TM *result);
finallyUse the Strftime function to format and get the last time string. For milliseconds, microseconds, nanoseconds, the output is also used. Example:
  1. #include <time.h>
  2. #include <sys/time.h>
  3. #include <stdio.h>
  4. int main ()
  5. {
  6. struct Timeval TV;
  7. Char strtime[32];
  8. Gettimeofday (&TV, NULL);
  9. struct TM *ptm = gmtime (&tv.tv_sec); Converts seconds into a struct TM form
  10. Strftime (Strtime, +, "%F%T", PTM);
  11. printf ("%s", strtime); Output accurate to seconds
  12. printf ("%ld micorseconds\n", (long) tv.tv_usec); Output microseconds
  13. return 0;
  14. }
Output result: 2011-09-14 03:22:42 427880 micorseconds another:Shaped likethe difference between the gmtime and the shape of the gmtime_t function is that the returned result of the gmtime is present in a static struct TM variable, which may be overwritten by a subsequent gmtime call, and we can provide ourselves a struct if we want to prevent overwriting. A tm-type variable that uses the Gmtime_r function to pass in the address of a variable of our own definition and save the result in it. This will avoid overwriting.  AboutCTime andAsctime such functions get the time string, which has the specified shape such as ("Wed June 30 21:49:08 1993 \ n") format, so unfavorable with us cannot be formatted.Note that the format ends with a newline character: ' \ n '.

Structure and related functions representing "Time" in Linux

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.