A _c language based on the use of the time function of C + +

Source: Internet
Author: User
Tags current time data structures function prototype local time month name time and date time interval microsoft c

C + + for the operation of the time there are many worthy of attention. 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 in the following:
Coordinated Universal Time (UTC):Reconciling the world, also known as the world Standard Time, is known as Greenwich Mean Time (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 calendar time is 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. Timing
The timing function in C/s + + 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 (Wal-clock) in MSDN. Where clock_t is the data type used to hold the time, in the Time.h file, we can find the definition of it:

Copy Code code as follows:

#ifndef _clock_t_defined
typedef long CLOCK_T;
#define _clock_t_defined
#endif

Obviously, 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), call the value returned by the clock () function plus 1. For the following example, you can use the formula clock ()/clocks_per_sec to calculate the elapsed time of a process itself:
Copy Code code as follows:

void Elapsed_time ()
{
printf ("Elapsed time:%u secs.\n", 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:
Copy Code code as follows:

#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\n", duration);
System ("pause");
}

On the author's machine, the results of the operation are as follows:
10000000 empty loops is 0.03000 seconds
We see that the clock timer is 1 milliseconds long and the precision of the timer is 1 milliseconds, so can we make the timing more accurate by changing the definition of clocks_per_sec by defining it a bit larger? 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. Data structures related to date and time
The TM structure can be used to obtain the date and time in standard C + +, and the TM structure is defined in Time.h as follows:
Copy Code code 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 represents Monday, to push */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
#endif

The 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:
Copy Code code as follows:

#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 a point of view (usually January 1, 1970 0:0 0 seconds) to the number of seconds (that is, calendar time) than the length of the number of digits can be expressed in the range? 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:
Copy Code code as follows:

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 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, calculating the time interval, displaying the time in different forms, and so on.
4.1 Getting the calendar time
We can use the time () function to get the calendar times, which is the prototype:
time_t Time (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 (NUL), 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:
Copy Code code as follows:

#include "time.h"
#include "stdio.h"
int main (void)
{
struct TM *ptr;
time_t lt;
Lt =time (NUL);
printf ("The Calendar time today is%d\n", lt);
return 0;
}

The results of the operation were related to the time, and the result I was running was:
The Calendar is 1122707619
1122707619 of these are the calendar times when I run 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 the date and time is what 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 the prototypes of the two functions:
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, the world standard Time obtained with the gmtime () function is July 30, 2005 7:18 20 seconds, then I use the localtime () function in China to get the local time is 8 hours later than the world standard Time, that is July 30, 2005 15:18 20 seconds. Here's an example:
Copy Code code as follows:

#include "time.h"
#include "stdio.h"
int main (void)
{
struct TM *local;
time_t T;
T=time (NUL);
Local=localtime (&t);
printf ("Local hour are:%d\n", local->tm_hour);
Local=gmtime (&t);
printf ("UTC Hour is:%d\n", local->tm_hour);
return 0;
}
The results of the operation are:
Local hour is:15
UTC Hour Is:7

4.3 fixed time format
We can display the time in a fixed format through the Asctime () function and the CTime () function, both of which return values are char* strings. The returned time format is:
Days of the week: minutes: \n\0 in second year
For example: Wed 02:03:55 1980\n\0
where \ n is a newline character, and the "is a null" to indicate 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 T is a non-empty time_t variable, then:
Copy Code code as follows:

printf (CTime (&t));
Equivalent to:
struct TM *ptr;
Ptr=localtime (&t);
printf (Asctime (PTR));

The results of the two printf statements in the following program are different (unless you set the local time zone to the time zone of World standard Time):
Copy Code code as follows:

#include "time.h"
#include "stdio.h"
int main (void)
{
struct TM *ptr;
time_t lt;
Lt =time (NUL);
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 in the format we want. Its prototype is as follows:
Copy Code code 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 decimal year with the century part
%z,%z the time zone name and returns a null character if the time zone name cannot be obtained.
Percent percent%
If you want to show what time it is, show it as a 12-hour system, as in the following procedure:
Copy Code code as follows:

#include "time.h"
#include "stdio.h"
int main (void)
{
struct TM *ptr;
time_t lt;
Char str[80];
Lt=time (NUL);
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

The following program displays the current full date:
Copy Code code as follows:

#include <stdio.h>
#include <time.h>
void Main (void)
{
struct TM *newtime;
Char tmpbuf[128];
time_t LT1;
Time (&LT1);
Newtime=localtime (&LT1);
Strftime (TMPBUF, 128, "This is%A, day%d '%B in the year%y.\n", NewTime);
printf (TMPBUF);
}
Run Result:
This is Saturday, and the July in the year 2005.

4.5 Calculate the length of the duration
Sometimes in practical applications, you calculate the length of time an event lasts, such as calculating 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:
Copy Code code as follows:

#include "time.h"
#include "stdio.h"
#include "Stdlib.h"
int main (void)
{
time_t start,end;
Start = time (NUL);
System ("pause");
End = Time (NUL);
printf ("The pause used%f seconds.\n", Difftime (End,start));//<-
System ("pause");
return 0;
}

The results of the operation 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 will replace the line with the following line of code with the "//<-" annotation on the above program:
printf ("The pause used%f seconds.\n", End-start);
The results of the operation are the same.
4.6 Decomposition time into calendar time
The decomposition time is the time structure that is saved by the components of year, month, day, time, minute and second, and is the TM structure in C/s + +. We can use the Mktime () function to convert the time represented by the TM structure to the calendar time. The 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 be calculated July 1, 1997 is the day of the week:
Copy Code code as follows:

#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 01 00:00:01 1997

Now notice that with the Mktime () function, is it possible for us to operate any time before now? Can you figure out August 15, 1945 is the day of the week in this way? 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.

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.