C + + Time function usage

Source: Internet
Author: User
Tags local time month name time and date microsoft c

C + + has a lot to pay attention to when it operates on time. Recently, many netizens in the technology group have also asked the question of the operation, acquisition and display of time in the C + + language. Below, in this article, I will mainly introduce the use of time and date in C + +.

You can have a lot of operations and time-of-use methods by learning a lot of the C + + libraries. But before you do, you need to know some of the concepts of "time" and "date", mainly the following:

Coordinated Universal time (UTC): Coordinated worlds, also known as World standard Times, is known as Greenwich Mean Time (Greenwich Mean time,gmt). For example, the time difference between the Chinese mainland and 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". This standard point of time for different compilers will vary, but for a compilation system, this standard point of time is constant, the compilation system time corresponding to the calendar time is measured by the standard time point, so you can say that the calendar time is "relative time", but no matter what time zone you are in, At the same time, the calendar time is the same for the same standard point.

Epoch: Point in time. The point-in-time is an integer in standard C + +, which is represented by the time of the moment and the number of seconds (that is, the calendar time) of the standard time point.

Clock tick: The clocking unit (rather than the number of ticks), the length of time a clock unit is controlled by the CPU. A clock tick is not a cycle of the CPU, but rather a basic unit of time in C + +.

We can use the Time.h header file in the ANSI standard library. The method used to define the time and date in this header file, both in terms of structure definition and naming, has a pronounced C-language style. Below, I'll show you how to use the time function of the date in C + +.

2. Timing

The timing function in C/s + + is clock (), and the data type associated with it is clock_t. In MSDN, the check for the clock function is defined as follows:

clock_t clock (void);

This function returns the number of CPU clock ticks (clock ticks) from "Open this program process" to "call clock () function in program", called 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:

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

It is clear that clock_t is a long shaping number. In the Time.h file, you also define a constant clocks_per_sec, which is used to indicate how many clock units are in a second, defined as follows:

#define CLOCKS_PER_SEC ((clock_t) 1000)

You can see that every 1 per thousand seconds (1 milliseconds), the value returned by the call to the clock () function increases by 1. As an example, you can use the formula clock ()/clocks_per_sec to calculate the run time of a process itself:

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 it takes for your machine to run a loop or 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\n", duration);
System ("pause");
}

On the author's machine, the results of the operation are as follows:

Time to does 10000000 empty loops is 0.03000 seconds

We can see that the clock timing unit is 1 milliseconds in length, and the accuracy of the timing is 1 milliseconds, so could we change the definition of the clocks_per_sec by making it larger, so that the timing is more accurate? By trying, you will find that this is not possible. In standard C/s + +, the smallest unit of timing is one millisecond.

3. Date and time-related data structures

in standard C + +, we can obtain the date and time by the TM structure, which is defined in Time.h as follows:

#ifndef _tm_defined
struct TM {
int tm_sec; /* seconds – The value interval is [0,59] */
int tm_min; /* min-value interval is [0,59] */
int tm_hour; /* When-the value interval is [0,23] */
int tm_mday; /* Date in one months-the value interval is [1,31] */
int Tm_mon; /* Month (starting from January, 0 for January)-the value range is [0,11] */
int tm_year; /* Year with a value equal to the actual year minus 1900 */
int tm_wday;     /* Week – The value interval is [0,6], where 0 represents Sunday, 1 for Monday, which pushes */int tm_yday; /* Number of days starting January 1 of each year – the value interval is [0,365], where 0 is January 1, 1 is January 2, and so on.
int tm_isdst; /* Daylight Saving time identifier, the TM_ISDST is positive when daylight savings is applied. Without daylight saving time, 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 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 represented by time_t (calendar time) is the number of seconds from a point in time (for example: January 1, 1970 0:0 0 seconds) to this time. In Time.h, we can also see that time_t is a long integer number:

#ifndef _time_t_defined
typedef long time_t; /* Time value */
#define _TIME_T_DEFINED/* Avoid repeating definitions time_t */
#endif

One might wonder: since time_t is actually a long integer, what about the number of seconds (that is, calendar time) that is beyond the range that a long shape can represent in the future, from one point in time (typically January 1, 1970 0:0 0 seconds) to that time? For a value of the time_t data type, the time it represents cannot be later than January 18, 2038 19:14 07 seconds. To be able to represent a longer period of time, some compiler vendors introduced 64-bit or even longer shaping numbers to hold the calendar time. For example, Microsoft uses the __time64_t data type in Visual C + + to save the calendar time and to get the calendar time through the _time64 () function (rather than by using the 32-bit word () function). This allows you to save the time before January 1, 3001 0:0 0 seconds (excluding that point in time).

In the time.h header file, we can also see some functions, all of which are functions with 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 TM that we normally see when the date and time are displayed separately:

struct TM * gmtime (const time_t *timer);

 

struct TM * localtime (const time_t * timer);

By looking at MSDN, we know that the value of the point-in-time (the value of the Time_t object) in Microsoft C + + + 7.0 is the number of seconds from December 31, 1899 0:0 0 seconds to that point in time, while other versions of Microsoft C + + And all of the different versions of Visual C + + are calculated as the number of seconds that elapsed from January 1, 1970 0:0 to 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 actions include taking the current time, calculating the time interval, displaying the time in different forms, and so on.

4.1 Get Calendar Time

We can use the time () function to get the calendar times, which are prototyped as:

time_t Time (time_t * timer);

If you have 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, from a point in time (for example: January 1, 1970 0:0 0 seconds) to now the number of seconds. If the argument is empty (NUL), the function will return the current calendar time only by the return value, such as the following example to display the calendar time:

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

The result of the operation was related to the time, and the result I was running was:

The Calendar time is 1122707619

1122707619 is the calendar time when I run the program. This is the number of seconds from January 1, 1970 0:0 to 0 seconds.

4.2 Getting the date and time

The date and time mentioned here are the information of the year, month, day, hour, minute and second that we usually say. From the 2nd section we already know that this information is stored in a struct called a TM, so how do you save a calendar time as an object of a TM structure?

The functions that can be used are gmtime () and localtime (), and the prototypes of these two functions are:

struct TM * gmtime (const time_t *timer);
struct TM * localtime (const time_t * timer);

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 now obtained with the gmtime () function is July 30, 2005 7:18 20 seconds, then the local time I get in China using the localtime () function will be 8 hours later than the world standard Time, i.e. 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 (NUL);
Local=localtime (&t);
printf ("Local Hour is:%d\n", local->tm_hour);
Local=gmtime (&t);
printf ("UTC Hour is:%d\n", local->tm_hour);
return 0;
}

The operating result is:

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 are char* strings. The time format returned is:

Day of the week month Date: minute: Second year \n\0
Example: Wed Jan 02:03:55 1980\n\0

where \ n is a newline character, and the. \ is a null char that indicates 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 with a fixed-format save time information through a TM structure, and CTime () generates a time string through the calendar time. In this case, the asctime () function simply fills the fields of the TM structure object into 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:

printf (CTime (&t));

Equivalent to:

struct TM *ptr;
Ptr=localtime (&t);
printf (Asctime (PTR));

So, the result of the two printf statements output from the following program is different (unless you set the local time zone to the time zone where world standard Time is located):

#include "time.h"
#include "stdio.h"
int main (void)
{
struct TM *ptr;
time_t lt;
Lt =time (NUL);
Ptr=gmtime (&LT);
printf (Asctime (PTR));
printf (CTime (&lt));
return 0;
}

Operation Result:

Sat Jul 30 08:43:03 2005
Sat Jul 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 string pointed to by the strdest, with a maximum of maxsize characters in the strdest, according to format commands in format point to String. The function returns the number of characters placed in the string pointed to by strdest.

The function strftime () operates somewhat like sprintf (): Identifies a collection of formatting commands that begin with a percent sign (%), 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 format commands are listed below, and they are case-sensitive.

%a shorthand for the day of the week
%A full name of the week
%b of the Month
Full name of the%B month
Time string for the date of%c standard
After two digits of the%c year
The day ordinal of a month in%d decimal notation
%d Month/day/year
%e the day ordinal of a month in a two-character field, in decimal notation
%F year-month-day
%g two digits of the year, using week-based
%G years, using week-based years
%h Abbreviated month name
%H 24-Hour Hour
%I 12-Hour Hour
%j decimal indicates the day ordinal of the year
%m the month represented by decimal
%M minutes in a 10 o'clock-hour representation
%n New Line character
%p equivalent display of the local AM or PM
%r 12 hours of time
%R display hours and minutes: hh:mm
%s number of seconds in decimal
%t Horizontal Tab
%T display time seconds: hh:mm:ss
%u days of the week, Monday for the first day (values from 0 to 6, Monday to 0)
%u year of the week, the Sunday as the first day (value from 0 to 53)
%V Week of the year, using week-based
%w Decimal Day of the week (value from 0 to 6, Sunday is 0)
%W Week of the year, Monday as the first day (value from 0 to 53)
Date string for%x standard
Time string for%x standard
%y decimal Year without century (values from 0 to 99)
%Y decimal year with century part
%z,%z the time zone name and returns a null character if the time zone name cannot be obtained.
Percent hundred percent semicolon

If you want to show what time it is now and display it as a 12-hour system, just like this procedure:

#include "time.h"
#include "stdio.h"
int main (void)
{
struct TM *ptr;
time_t lt;
Char str[80];
Lt=time (NUL);
Ptr=localtime (&LT);
Strftime (str,100, "It's now%I%p", PTR);
printf (str);
return 0;
}

The result of this operation is:
It's now 4PM

The following program displays the current full date:

#include <stdio.h>

 

#include <time.h>

void Main (void)
{
struct TM *newtime;
Char tmpbuf[128];
time_t LT1;
Time (&AMP;LT1);
Newtime=localtime (&AMP;LT1);
Strftime (Tmpbuf, "Today is%A, day%d of%B in the year%y.\n", NewTime);
printf (TMPBUF);
}

Operation Result:

Today is Saturday, Day's July in the year 2005.

4.5 Calculating the length of duration

Sometimes in the actual application to calculate the duration of an event, such as the calculation of typing speed. In the 1th section of the timing section, I've used the clock function to give an example. The Clock () function can be accurate to the millisecond level. Also, 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 returned in seconds by the function is double, this does not mean that the time has the same precision as a double, which is what its arguments think (time_t is calculated 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 (NUL);
System ("pause");
End = Time (NUL);
printf ("The pause used%f seconds.\n", Difftime (End,start));//<-
System ("pause");
return 0;
}

The result of the operation is:
Please press any key to continue ...
The pause used 2.000000 seconds.
Please press any key to continue ...

It can be imagined that the pause time is not so coincidence that it is a full 2 seconds. In fact, you replace the one line with the "//<-" comment in the above program with the following line of code:

printf ("The pause used%f seconds.\n", End-start);

The result is the same.

4.6 Decomposition time converted to calendar time

The decomposition time is the time structure saved by year, month, day, hour, minute, second and so on, which is the TM structure. We can use the Mktime () function to convert the time represented by the TM structure into a calendar time. Its function prototype is as follows:

time_t mktime (struct TM * timeptr);

The return value is the converted calendar time. So that we can set a decomposition time, and then the time to operate, the following example can be calculated 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;
}

Operation Result:

Tue Jul 01 00:00:01 1997

Now notice that with the Mktime () function, is it possible for us to manipulate any time before now? Can you figure out August 15, 1945 is the day of the week? The answer is in the negative. Because this time is before January 1, 1970, so in most compilers, such a program can be compiled through, but the runtime will be abnormally terminated.


Cocos2dx

void Player::time_ () {int ctime = (int) function::getinstance ()->getcurrtime (); log ("CTime [%d]", ctime);    struct TM *local;    time_t T;    Time (&t);    Local=localtime (&t);    Log ("Local is  :%d,%d,%d \ n", Local->tm_hour, Local->tm_yday, local->tm_wday);        time_t dtime = (time_t) this->getlogintimestamp ();    struct TM *dlocal;    Dlocal=localtime (&dtime);    Log ("Local is  :%d,%d,%d \ n", Dlocal->tm_hour, Dlocal->tm_yday, dlocal->tm_wday);    return;}



int64_t Function::getcurrtime () {time_t rawtime;time (&rawtime); return rawtime;} Long function::gettimesec () {struct Timeval TV;          Gettimeofday (&tv,null);          return tv.tv_sec * + tv.tv_usec/1000;  } Long function::gettimeusec () {struct Timeval TV;          Gettimeofday (&tv,null);          return tv.tv_usec;  }




C + + Time function usage

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.