Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - Can someone tell me which function in C language can record time?
Can someone tell me which function in C language can record time?
Date and time in C/C++

abstract:

Starting with the introduction of basic concepts, this paper discusses the data structure and functions used in date and time operation in C/C++, and expounds the aspects of timing, time acquisition, time calculation and display format. This paper also shows you the detailed usage of various functions and data structures declared in the time.h header file through a large number of examples.

Key words:

UTC (Universal Standard Time), Calendar Time (Calendar Time), Era (Time Point), Clock Tick (Clock Tick Unit).

1. concept

In C/C++, there are many noticeable problems in string manipulation. Similarly, the manipulation of time by C/C++ also has many points worthy of attention. Recently, many netizens in the technical group have asked many questions about the operation, acquisition and display of time in C++ language. Next, in this article, the author will mainly introduce the use of time and date in C/C++.

By learning many C/C++ libraries, you can operate and use your time in many ways. But before that, you need to know some concepts of "time" and "date", mainly as follows:

Coordinated Universal Time (UTC): Coordinated Universal Time, also known as Universal Standard Time, also known as Greenwich Mean Time (GMT). For example, the time difference between Chinese mainland and UTC is +8, which means UTC+8. The United States is UTC-5.

Calendar time: Calendar time is the time expressed by "the number of seconds elapsed from a standard time point to this time". This standard time point will be different for different compilers, but for a compilation system, this standard time point is unchanged, and the calendar time corresponding to the time in the compilation system is measured by this standard time point, so it can be said that the calendar time is "relative time", but no matter which time zone you are in, the calendar time at the same standard time point at the same time is the same.

Era: point in time. The time point is an integer in the standard C/C++, which is expressed by the number of seconds between the time at this time and the standard time point (that is, the calendar time).

Clock ticking: Clock ticking unit (not called clock ticking). The time of the clock ticking unit is controlled by the central processor. Clock beat is not a clock cycle of CPU, but a basic time unit of C/C++.

We can use the time.h header file in the ANSI standard library. The method used to define time and date in this header file has obvious C language style in both structural definition and naming. Next, I will explain how to use the time function of date in C/C++.

Step 2: Timing

The timing function in C/C++ is clock (), and its related data type is clock _ t. In MSDN, Chad defines the clock function as follows:

clock _ t clock(void);

This function returns the number of CPU clock ticks between "starting the program process" and "calling the clock () function in the program", which is called wal-clock in MSDN. Where clock_t is a data type used to save time, and its definition can be found in the time.h file:

#ifndef _CLOCK_T_DEFINED

Typedef long clock _ t;;

# Definition _ Clock _ Time _ Definition

#endif

Obviously, clock_t is a long integer. In the time.h file, a constant CLOCKS_PER_SEC is also defined to indicate how many clock timing units there will be in one second, which is defined as follows:

# Define the number of clocks per second ((clock_t) 1000)

You can see that every thousandth of a second (1 millisecond), the value returned by calling the clock () function increases by 1. For example, you can use the formula clock()/CLOCKS_PER_SEC to calculate the running time of the process itself:

void elapsed_time()

{

Printf ("Running time: %u seconds. \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 cycle or handle other events:

# contains "stdio.h"

# contains "stdlib.h"

# contains "time.h"

int main( void)

{

Dragon I =1000000l;

Clock_t starts and ends;

Double duration;

/* Measure the duration of the event */

Printf ("The time to do %ld empty loops is", i);

Start = clock ();

When (I-)

finish = clock();

duration =(double)(finish-start)/CLOCKS _ PER _ SEC;

Printf( "%f seconds \n ",duration);

System ("suspended");

}

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

The time to do 1000000 empty cycles is 0.03000 seconds.

Above we see that the length of the clock timing unit is 1ms, so the timing accuracy is1ms. Then, can you change the definition of CLOCKS_PER_SEC to make the timing accuracy higher? By trying, you will find it impossible. In the standard C/C++, the minimum time unit is 1 millisecond.

3. Data structure related to date and time

In the standard C/C++, we can get the date and time through the tm structure, which is defined in time.h as follows:

#ifndef _TM_DEFINED

Structure tm {

Int tm _ sec/* seconds–the interval between values is */

Int tm _ min/* minutes-The interval between values is */

Int tm _ hour/* when-value interval is */

Int tm _ mday/* Date in a month-the range is, where 0 means Sunday, 1 means Monday, and so on */

Int tm _ yday/* Number of days per year starting from 65438+1 October 1–the value range is, where 0 means 65438+1 October1and1means 65438+/kloc-0.

Int tm _ isdst/* daylight saving time identifier. When daylight saving time is implemented, tm_isdst is positive. Without daylight saving time, tm_isdst is 0; When the situation is unknown, Tm_isdst () is negative. */

};

#define _TM_DEFINED

#endif

The ANSI C standard says that the time of using tm structure is expressed as breakdown time. Calendar time is represented by the data type of time_t, and the time represented by time_t is the number of seconds from a certain point in time (for example: 1970 65438+ 10 month 1: 00: 00). 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 defining time_t */

#endif

You may wonder: Since time_t is actually a long integer, what should I do if the number of seconds from a certain point in time (generally 1970 65438+65438 10: 00: 00 on October) to that point in time (that is, calendar time) is beyond the range that a long integer can represent? For the value of time_t data type, the time it represents cannot be later than 65438+ 18, 19: 08, 2038+ 14: 07. In order to express a longer time, some compiler manufacturers have introduced 64-bit or even longer integers to save calendar time. For example, Microsoft uses __time64_t data type to save the calendar time in Visual C++, and obtains the calendar time through _time64 () function (instead of using 32-bit time () function), which can save 300 1 year 1 month 1 day at 0: 00: 00 (.

In the header file of time.h, we can also see some functions with time_t as parameter type or return value type:

double difftime(time _ t time 1,time _ t time 0);

time _ t mktime(struct TM * time ptr);

time _ t time(time _ t * timer);

char * ASC time(const struct TM * time ptr);

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) into the time format tm that we usually see to display the year, month, day, minute and second respectively:

struct TM * GM time(const time _ t * timer);

struct TM * local time(const time _ t * timer);

By consulting MSDN, we can know that the value of time point in Microsoft C/C++ 7.0 (the value of time_t object) is the number of seconds from189965438+February 3 1 to this time point, while other versions of Microsoft C/C++ and all different versions of Visual C++ are calculated from 60.

4. Functions related to date and time and their applications

In this section, I will show you how to use the functions declared in time.h to manipulate time. These operations include obtaining the current time, calculating the time interval, displaying the time in different forms and so on.

4. 1 Get the calendar time

We can get the calendar Time through the time () function, and its prototype is: time _ t time (time _ t * timer);

If the parameter timer has been declared, you can return the current calendar time from the parameter timer, or you can return the current calendar time by returning the value, that is, the number of seconds from a certain time point (for example: 1970 1.00+0.00) to the current time. If this parameter is null, the function will return the current calendar time only by the return value, as shown in the following example:

# contains "time.h"

# contains "stdio.h"

int main(void)

{

struct tm * ptr

time _ t lt

Lt = time (nul);

Printf ("The current calendar time is %d\n", lt);

Returns 0;

}

The result of the operation is related to the time at that time. The result of my operation at that time was:

The current calendar time is1122707619.

Where 1 122707 19 is the calendar time when I run the program. That is, seconds from 1970 65438+ 10 month 1, 0: 00, 0: 00.

4.2 Purchase Date and Time

The date and time mentioned here are the information we usually say such as year, month, day, hour, minute and second. From section 2, we already know that all this information is saved in a structure called tm, so how to save a calendar time as an object with tm structure?

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

struct TM * GM time(const time _ t * timer);

struct TM * local time(const time _ t * timer);

The gmtime () function converts the calendar time into universal standard time (GMT) and returns a tm structure to save the time, while the localtime () function converts the calendar time into local time. For example, the universal time obtained by using the gmtime () function is 7: 00 on July 30th, 2005, so the local time obtained by using the localtime () function in China will be 8 hours later than the universal time, that is, July 30th, 2005 is 65,438+08: 20. Here's an example:

# contains "time.h"

# contains "stdio.h"

int main(void)

{

struct tm * local

time _ t t

T = time (nul);

local=localtime。 t);

Printf ("local time is: %d\n", Local-& gt;; TM _ hour);

local=gmtime。 t);

Printf("UTC hour is: %d\n ",local-& gt;; TM _ hour);

Returns 0;

}

The running result is:

The local time is: 15

UTC time is: 7.

4.3 fixed time format

We can display the time in a fixed format through asctime () function and ctime () function, and the return values of both functions are char * strings. The returned time format is:

Day, month, day, hour: minute: second year \n\0

For example: wedjan 02 02: 03: 551980 \ n \ 0

Where \n is a line break and \0 is a null character, indicating the end of the string. The following are prototypes of two functions:

char * ASC time(const struct TM * time ptr);

char * ctime(const time _ t * timer);

Among them, asctime () function is to generate a fixed format string for saving time information through tm structure, while ctime () is to generate a time string through calendar time. In this case, the asctime () function only needs to fill the fields in the tm structure object in the corresponding position of the time string, while the ctime () function needs to refer to the local time setting, convert the calendar time into the local time, and then generate the formatted string. Next, if t is a non-empty time_t variable, then:

printf(ctime(& amp; t));

Equivalent to:

struct tm * ptr

ptr=localtime。 t);

printf(ASC time(ptr));

Then, the output results of the two printf statements in the following program are different (unless you set the local time zone as the time zone of universal standard time):

# contains "time.h"

# contains "stdio.h"

int main(void)

{

struct tm * ptr

time _ t lt

Lt = time (nul);

ptr = gmtime(& lt; );

printf(ASC time(ptr));

printf(ctime(& lt; ));

Returns 0;

}

Running results:

Saturday, 30 July 2005 08: 43: 03

Saturday, 30 July 2005 16:43:03

4.4 Custom Time Format

We can use the strftime () function to format the time we want. Its prototype is as follows:

size_t strftime(

char *strDest,

size_t maxsize,

Const char * format,

const struct tm *timeptr

);

We can put the time information saved in timeptr into the string pointed by strtest according to the format command pointing to the string, and the maximum number of maxsize characters is stored in strtest. This function returns the number of characters in the string pointed by strDest.

The operation of strftime () function is somewhat similar to sprintf (): it recognizes the format command set starting with percent sign (%) and puts the print format result in a string. The format command explains the exact representation of various date and time information in the string strDest. Other characters in the format string are put into the string as they are. The format commands are listed below. They are case-sensitive.

Abbreviation for day of the week%.

Full name of% day of the week.

Abbreviation for %b month minutes

Full name of %B month

Time series of %c standard dates

Last two digits of %C year

What day of the month does %d represent in decimal?

%D month/day/year

%e In the two-character field, what day of the month is expressed in decimal?

%F year-month-day

Last two digits of year %g, using week-based year.

%G years, using week-based years

Short month name of %h

%H 24-hour clock

%I 12 hours

What day of the year does %j represent in decimal?

%m decimal month

%M minutes in decimal time

%n new line character

%p equivalent display of local AM or PM.

%r 12 hours

%R displays hours and minutes: hh: mm

Fractional seconds of %S

%t horizontal tab

% t is displayed in minutes and seconds: hh:mm:ss.

%u What day is Monday, the first day (values range from 0 to 6, and Monday is 0)?

%U Sunday is the first day of the week of the year (value from 0 to 53)?

%V What week ordinal of a year, use a week-based year.

%w What day of the week is it (values range from 0 to 6, and Sunday is 0)

%W What week ordinal of a year is Monday the first day (value between 0 and 53)?

%x standard date string

Time series of %X standard

%y Decimal year without century (value from 0 to 99)

Decimal year of %Y with century part

%z, %Z Time zone name, or empty character if time zone name cannot be obtained.

%% percent symbol

If you want to display what time it is, and display 12 hour, just like the following program:

# contains "time.h"

# contains "stdio.h"

int main(void)

{

struct tm * ptr

time _ t lt

String [80];

Lt = time (nul);

ptr = local time(& lt; );

Strftime(str, 100, "Now it's %I %p", ptr);

printf(str);

Returns 0;

}

The running results are as follows:

It's 4 p.m.

The following program displays the current completion date:

# include & ltstdio.h & gt

# include & lttime.h & gt

Invalid master (invalid)

{

struct tm * newtime

char tmpbuf[ 128];

time _ t lt 1;

Time (< 1);

new time = local time(& lt; 1);

Strftime( tmpbuf, 128, "Today is the %d day %A of year %Y, \n", newtime);

printf(tmpbuf);

}

Running results:

Today is Saturday, July 30th, 2005.

4.5 Calculate the length of the duration

In practical applications, it is sometimes necessary to calculate the duration of an event, such as calculating the typing speed. In the timing part of 1, I have given an example with the clock function. The Clock () function can be accurate to the millisecond level. At the same time, we can also use the difftime () function, but it can only be accurate to seconds. This function is defined as follows:

double difftime(time _ t time 1,time _ t time 0);

Although the time interval in seconds returned by this function is of type double, it does not mean that time has the same precision as double, which is felt by its parameters (time_t is calculated in seconds). For example, the following program:

# contains "time.h"

# contains "stdio.h"

# contains "stdlib.h"

int main(void)

{

Time_t starts and ends;

Start = time (nul);

System ("suspended");

End = time (nul);

Printf ("Paused for %f seconds. \n ",difftime(end,start)); //& lt; -

System ("suspended");

Returns 0;

}

The running results are as follows:

Please press any key to continue ...

The pause took 2.0000000 seconds.

Please press any key to continue ...

As you can imagine, the pause time is not so coincidental as 2 seconds. In fact, you use the above program as "//

Printf ("Paused for %f seconds. \n ",end-start);

The running result is the same.

4.6 Turn time warp into calendar time.

The decomposition time mentioned here is the time structure saved in units of year, month, day, hour, minute and second, which is the tm structure in C/C++. We can use mktime () function to convert the time represented by tm structure into calendar time. Its functional prototype is as follows:

time _ t mktime(struct TM * time ptr);

The return value is the converted calendar time. In this way, we can do a decomposition time first, and then operate on this time. The following example can calculate the date of the week of July 1997 1:

# contains "time.h"

# contains "stdio.h"

# contains "stdlib.h"

int main(void)

{

struct TM t;

Time 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(& amp; t);

printf(ctime(& amp; t _ of _ day);

Returns 0;

}

Running results:

Tuesday 06 5438+0 00: 00: 06 5438+01997

Now notice that with the mktime () function, can we operate at any time before now? Can you work out the day of August 1945 by this method? The answer is no, because this time is before 1970 65438+ 10/month, so in most compilers, although such a program can be compiled, its runtime will terminate abnormally.