A very good introduction C, C + + in the use of Time functions __ function

Source: Internet
Author: User
Tags function prototype local time month name time and date microsoft c
The date and time time_t and struct TM conversions in C + +
Summary:
Starting from the introduction of basic concepts, this paper discusses the data structure and functions used in the operation of date and time in C/A + +, and expounds the timing, time acquisition, time calculation and display format. This article also shows you the detailed use of various functions and data structures declared in the Time.h header file through a large number of examples. Keywords: UTC (World Standard Time), calendar times (Calendar time), epoch (point-in-time), clock tick (clock timing unit)
1. Concept
There are many noteworthy problems with the operation of the string in C + +, and there are many noteworthy points for the operation of C + + for time. Recently, in the technical group, many netizens have asked the C + + language on the operation of time, access and display, and so on. Below, in this article, the author will mainly introduce the time and date of the use method in C + +. You can have a lot of ways to manipulate and use time by learning many of the C + + libraries. But before that you need to know some concepts of "time" and "date", mainly the following: Coordinated Universal Time (UTC): Coordinated world, also known as the world Standard Time, which is known as Greenwich standard Times (Greenwich Mean TIME,GMT). In China, for example, the time difference from UTC is +8, which is utc+8. The United States is UTC-5. Calendar time: The time that is represented by the number of seconds elapsed from a standard point in time to this time. This standard point in time is different for various compilers, but for a compilation system, this standard time point is invariant, the time corresponding to the calendar time in the compilation system is measured by the standard point of time, so you can say that calendar time is "relative time", but no matter which time zone you are in, At the same time, the calendar time is the same for the same standard point. Epoch: Time point. A time point is an integer in standard C + + that is represented by the number of seconds (that is, the calendar time) that differs from the standard point in time. Clock tick: Clock timing unit (not called clock tick), the length of a clock timer is controlled by the CPU. A clock tick is not a clock cycle of the CPU, but a basic timing unit for C/S. We can use the Time.h header file in the ANSI standard library. The method used for the time and date defined in this header file, whether in structure definition or naming, has an obvious C language style. Below, I will explain how to use the time function of the date in C + +. 2. The timing function in the timed C + + + + is clock (), and its associated data type is clock_t. In MSDN, the clock function is identified as follows: clock_t clock (void); This function returns the number of CPU clock timing units (clock tick) between the time the "start this program process" and the call to clock () function in the program), which is called the Wall Clock Time (Wall-clock) in MSDN. Where clock_t is the data type used to hold the time, in Time.h file, we can find the definition of it: #ifndef _clock_t_defined
typedef long CLOCK_T;
#define _clock_t_defined
#endif It is obvious that clock_t is a long shaping number. In the time.h file, a constant clocks_per_sec is also defined to indicate how many clock ticks will be in a second, defined as follows: #define CLOCKS_PER_SEC ((clock_t) 1000) You can see that every 1 per thousand seconds (1 milliseconds) is seen, and the value returned by the call to the clock () function is added to 1. For the following example, you can use the formula clock ()/clocks_per_sec to calculate the elapsed time of a process itself: void Elapsed_time ()
{
printf ("Elapsed time:%u secs.", clock ()/clocks_per_sec);
Of course, you can also use the clock function to calculate how long your machine runs a loop or how much time it takes to handle other events: #include "stdio.h"
#include "Stdlib.h"
#include "time.h" int main (void)
{
Long i = 10000000L;
clock_t start, finish;
Double duration;
/* Measure the duration of an event/
printf ("Time to does%ld empty loops is", i);
start = Clock ();
while (i--);
finish = Clock ();
Duration = (double) (finish-start)/clocks_per_sec;
printf ("%f seconds", duration);
System ("pause");
On the author's machine, the results of the operation are as follows: 10000000 empty loops is 0.03000 seconds above we see the clock Timer unit length is 1 milliseconds, then the timing precision is 1 milliseconds, then we can change the Clocks_ The definition of per_sec, by defining it larger, so that the accuracy of the timing is higher. By trying, you'll find that this is not going to work. The smallest unit of timekeeping in standard C/s is one millisecond. 3. Date and time related data structures in standard C/A, we can obtain the date and time by the TM structure, and the TM structure is defined in Time.h as follows: #ifndef _tm_defined
struct TM {
int tm_sec; /* SEC – The value range is [0,59] * *
int tm_min; /* Divide-take value range is [0,59] * *
int tm_hour; /* Time-value range is [0,23] * *
int tm_mday; /* One months date-value range for [1,31] * *
int Tm_mon; /* Month (starting from January, 0 represents January)-the value range is [0,11] * *
int tm_year; /* Year with the value equal to the actual year minus 1900 * *
int tm_wday; /* Week – The value range is [0,6], of which 0 represents Sunday, 1 for Monday, and so on * *
int tm_yday; /* The number of days from January 1 of each year – the value interval is [0,365], of which 0 represents January 1, 1 is January 2, and so on.
int tm_isdst; /* Daylight Saving time identifier, TM_ISDST is positive when implementing daylight savings. When daylight saving time is not implemented, the TM_ISDST is 0 and TM_ISDST () is negative when the situation is not known. */
};
#define _tm_defined
The #endif ANSI C standard says this time for using the TM structure is expressed as the decomposition time (broken-down times). The calendar time is represented by the time_t data type, and the time (calendar time) represented by time_t is the number of seconds from one point of time (for example: January 1, 1970 0:0 0 seconds) to this point. In Time.h, we can also see that time_t is a long integer: #ifndef _time_t_defined
typedef long time_t; /* Time Value * *
#define _TIME_T_DEFINED/* Avoid duplicate definitions time_t * *
#endif you may have a question: since time_t is actually a long integer, one day in the future, from one point of time (typically January 1, 1970 0:0 0 seconds) to the number of seconds (that is, calendar time) beyond the range of numbers that can be represented by long shaping. For a value of the time_t data type, the time it represents cannot be as late as January 18, 2038 19:14 07 seconds. To be able to represent a longer time, some compiler vendors have introduced 64-bit or even longer cosmetic numbers to hold the calendar time. For example, Microsoft uses the __time64_t data type in Visual C + + to hold the calendar time, and through the _time64 () function to obtain the calendar time (instead of using the 32-bit word () function), This allows you to save the time before January 1, 3001 0:0 0 seconds (excluding that point) from the data type. In the time.h header file, we can also see functions that are either time_t as parameter types or return value types: Double Difftime (time_t time1, time_t TIME0);
time_t mktime (struct TM * timeptr);
time_t Time (time_t * timer);
char * asctime (const struct TM * timeptr);
char * CTime (const time_t *timer); In addition, Time.h also provides two different functions to convert the calendar time (an integer represented by time_t) to the time format that we normally see when the month and a minute are displayed separately tm:struct TM * gmtime (const time_t *timer);
struct TM * localtime (const time_t * timer); By looking at MSDN, we can see that the value of the time point (the value of the Time_t object) in Microsoft C/s + + 7.0 is the number of seconds elapsed from December 31, 1899 0:0 0 seconds to that point, while the other various versions of Microsoft C + + And all different versions of Visual C + + are calculated by the number of seconds from January 1, 1970 0:0 0 seconds to that point in time. 4. Functions and applications related to date and time
In this section, I'll show you how to use the functions declared in time.h to manipulate time. These operations include taking the current time, counting the time interval, displaying the time in different forms, and so on. 4.1 To get the calendar time we can get the calendar time by using the time_t () function, which is the prototype: time_t * timer); If you have already declared the parameter timer, you can return the current calendar time from the parameter timer, and return the current calendar time by returning the value, that is, the number of seconds from one point of time (for example: January 1, 1970 0:0 0 seconds) to the present time. If the parameter is null (NULL), the function returns the current calendar time only through the return value, for example, the following example is used to display the present calendar time: #include "time.h"
#include "stdio.h"
int main (void)
{
struct TM *ptr;
time_t lt;
Lt =time (NULL);
printf ("The Calendar Time is%d", lt);
return 0;
The result of the run was related to the time, and the result I ran was that the calendar time of now 1122707619, 1122707619 of which was the calender when I ran the program. That is, the number of seconds from January 1, 1970 0:0 0 seconds to this time. 4.2 Get date and time here is the date and time that we usually say the year, month, day, time, minutes, seconds and other information. As we know from the 2nd section that this information is stored in a struct called TM, how do you save a calendar time as an object of a TM structure? The functions that can be used are gmtime () and localtime (), which are prototypes of the struct TM * gmtime (const time_t *timer);
struct TM * localtime (const time_t * timer); where the Gmtime () function converts the calendar time to world standard Time (that is, GMT) and returns a TM structure to hold the time, while the localtime () function converts the calendar time to local time. For example, now the world standard Time with the Gmtime () function is July 30, 2005 7:18 20 seconds, then I use the localtime () function in China to obtain the local time than the time standard time is 8 hours later, that is, July 30, 2005 15:18 20 seconds. Here's an example: #include "time.h"
#include "stdio.h"
int main (void)
{
struct TM *local;
time_t T;
T=time (NULL);
Local=localtime (&t);
printf ("Local hour are:%d", local->tm_hour);
Local=gmtime (&t);
printf ("UTC Hour is:%d", local->tm_hour);
return 0;
The result of the run is: Local hour is:15
UTC hour is:7 4.3 fixed time format We can display time in a fixed format through the Asctime () function and the CTime () function, both of which return values are char*-type strings. The returned time format is: Days of the Week: minutes: Second year
For example: Wed 02 02:03:55 1980 One is a newline character, which is a null, representing the end of the string. The following is a prototype of two functions: char * asctime (const struct TM * timeptr);
char * CTime (const time_t *timer); where the asctime () function generates a string of fixed-format save time information through a TM structure, and CTime () generates a time string by calendar time. In this case, the asctime () function simply fills the domain of the TM structure object to the corresponding position of the time string, and the CTime () function needs to refer to the local time setting, convert the calendar time to local time, and then generate the formatted string. Below, if LT is a non-empty time_t variable, then: printf (CTime (<)); Equivalent to: struct TM *ptr;
Ptr=localtime (<);
printf (Asctime (PTR)); So, the result of the output of the two printf statements in the following program is different (unless you set the local time zone to the time zone of World standard Time): #include "time.h"
#include "stdio.h"
int main (void)
{
struct TM *ptr;
time_t lt;
Lt =time (NULL);
Ptr=gmtime (<);
printf (Asctime (PTR));
printf (CTime (<));
return 0;
Run Result: Sat June 30 08:43:03 2005
Sat June 30 16:43:03 2005 4.4 Custom Time format We can use the strftime () function to format the time as we want. Its prototype is as follows: size_t strftime (
Char *strdest,
size_t MaxSize,
const Char *format,
Const struct TM *timeptr
); We can place the time information stored in the timeptr in the strdest-pointing string according to the format pointing to the Formatting command in the string, and maxsize characters to the strdest. The function returns the number of characters placed in the string pointed to strdest. The operation of the function strftime () is somewhat similar to the sprintf (): The collection of format commands that begin with the percent sign (%) is recognized, and the formatted output is placed in a string. The format command describes the exact representation of the various date and time information in the string strdest. Other characters in the format string are placed in the string as is. The formatting commands are listed below, and they are case-sensitive. %a Day of the week
%A the full name of the week
%b of the Month
Full name of%B month
Time series for the%c standard date
Rear two digits of%c year
The first day of the month in%d decimal notation
%d Month/day/year
%e in a two-character field, the first day of the month in decimal notation
%F year-month-day
Two digits of%g year, using week-based years
%G years, using weeks based
%h Abbreviated month name
%H 24-hour system hours
%I 12-hour hours
%j decimal representation of the first day of the year
Month in%m decimal notation
Number of minutes represented by%m 10 o'clock
%n New Line character
%p the equivalent display of a local AM or PM
%r 12 hours.
%R display hours and minutes: hh:mm
%s decimal number of seconds
%t Horizontal Tab
%T when displayed: Hh:mm:ss
%u days of the week, Monday is the first day (values from 0 to 6, Monday to 0)
%u week of the year, make Sunday the first day (values from 0 to 53)
%V the first weeks of the year, using a week based year
%w decimal representation of the week (values from 0 to 6, Sunday to 0)
%w Week of the year, Monday is the first day (value from 0 to 53)
The date string of the%x standard
%x Standard Time series
%y decimal Year without century (values from 0 to 99)
%Y 10 year of the century part
%z,%z the time zone name and returns a null character if the time zone name cannot be obtained.
Percent percent semicolon if you want to show what time it is, and show it as a 12-hour system, like the following procedure: #include "time.h"
#include "stdio.h"
int main (void)
{
struct TM *ptr;
time_t lt;
Char str[80];
Lt=time (NULL);
Ptr=localtime (<);
Strftime (str,100, "It is now%I%p", PTR);
printf (str);
return 0;
The results of the operation are:
It is now 4PM and the following program displays the current full date: #include
#include void main (void)
{
struct TM *newtime;
Char tmpbuf[128];
time_t LT1;
Time (<1);
Newtime=localtime (<1);
Strftime (TMPBUF, 128, "This is%A, day%d of%B in",%Y);
printf (TMPBUF);
Run Result: Today is Saturday, day of July in the year 2005. 4.5 Calculating the duration of the length of time sometimes in practical applications to calculate the duration of an event, such as the calculation of typing speed. In the 1th timer section, I've used the clock function to give an example. The Clock () function can be accurate to the millisecond level. At the same time, we can use the Difftime () function, but it is only accurate to seconds. The function is defined as follows: Double Difftime (time_t time1, time_t TIME0); Although the time interval in seconds that the function returns is double, this does not mean that the time has the same precision as the double, which is determined by its arguments (time_t is measured in seconds). For example, the following procedure: #include "time.h"
#include "stdio.h"
#include "Stdlib.h"
int main (void)
{
time_t start,end;
Start = time (NULL);
System ("pause");
End = Time (NULL);
printf ("The pause used%f seconds.", Difftime (End,start));//<-
System ("pause");
return 0;
The results of the run are:
Please press any key to continue ...
The pause used 2.000000 seconds.
Please press any key to continue ... As you can imagine, the pause time is not so fortuitous for exactly 2 seconds. In fact, you replace the line with the "//<-" annotation in the above program with the following line of code: printf ("The pause used%f seconds.", End-start); The results of the operation are the same. 4.6 Decomposition time to calendar time the decomposition time is the time structure that is saved by year, month, day, time, minute and second, and is the TM structure in C + +. We can use the Mktime () function to convert the time represented by the TM structure to the calendar time. Its function prototype is as follows: time_t mktime (struct TM * timeptr); The return value is the converted calendar time. So we can start with a decomposition time, and then the time to operate, the following example can calculate July 1, 1997 is the day of the week: #include "time.h"
#include "stdio.h"
#include "Stdlib.h"
int main (void)
{
struct TM T;
time_t T_of_day;
t.tm_year=1997-1900;
t.tm_mon=6;
T.tm_mday=1;
t.tm_hour=0;
t.tm_min=0;
T.tm_sec=1;
t.tm_isdst=0;
T_of_day=mktime (&t);
printf (CTime (&t_of_day));
return 0;
Run Result: Tue June 01 00:00:01 1997 now notice, with the Mktime () function, is not we can operate any time before now. You can calculate the August 15, 1945 of the week by this method. The answer is in the negative. Because this time is before January 1, 1970, so in most compilers, such a program can be compiled, but the runtime terminates abnormally. 5. Summary This article introduces the concepts of date and time in standard C + +, and describes how to use these functions and data structures through various examples. The author thinks that some concepts related to time are very important, and understanding these concepts is the basis of understanding the transformation of various time formats, and also the basis of applying these functions and data structures. Article Source: Internet

original address from the Internet
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.