Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to carry on C time function Overview

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

How to carry on the C time function overview, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

1. Concept

There are many noticeable problems in the operation of string in C _ + _. Recently, many netizens in the technology group have asked questions about the operation, acquisition and display of time in C++ language for many times. Next, in this article, the author will mainly introduce the use of time and date in C _ chart +.

You can have a lot of ways to manipulate and use time by learning many Cmax Clipper + libraries. But before you do that, you need to understand some concepts of "time" and "date". There are mainly the following:

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

Calendar Time: calendar time, which is expressed as the number of seconds elapsed from a standard point in time to this time. This standard time point will be different for different compilers, but for a compilation system, this standard time point is constant, 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 calendar time is "relative time", but no matter which time zone you are in, at the same time for the same standard time point, the calendar time is the same.

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

Clock tick: a clock timing unit (instead of calling it a clock tick). The length of time of a clock timing unit is controlled by the CPU. A clock tick is not a clock cycle of a CPU, but a basic timing unit of the Cmax plus.

We can use the time.h header file in the ANSI standard library. The methods used for the time and date defined in this header file, whether in structure definition or naming, have a clear C language style. Next, I'll show you how to use the time feature of dates in CCompact +.

2. Timing

The timing function in C _ clock_t + is clock (), and the associated data type is clock_t. In MSDN, the clock function is defined as follows:

Clock_t clock (void)

This function returns the number of CPU clock timing units (clock tick) from "starting this program process" to "calling the clock () function in the program", which is called wall clock time (wal-clock) in MSDN. Where clock_t is the data type used to save 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

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 timing units there will be in a second, which is defined as follows:

# define CLOCKS_PER_SEC ((clock_t) 1000)

You can see that every 1/1000 seconds (1 millisecond), the value returned by calling the clock () function is incremented by 1. For 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./n", clock () / CLOCKS_PER_SEC)

}

Of course, you can also use the clock function to calculate how long it takes 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 do ld empty loops is", I)

Start = clock ()

While (iMurt -)

Finish = clock ()

Duration = (double) (finish-start) / CLOCKS_PER_SEC

Printf ("f seconds/n", duration)

System ("pause")

}

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

Time to do 10000000 empty loops is 0.03000 seconds

Above we see that the length of the clock timing unit is 1 millisecond, so the timing accuracy is also 1 millisecond, so can we make the timing accuracy higher by changing the definition of CLOCKS_PER_SEC and making it larger? By trying, you will find that this will not work. The smallest unit of time in the standard CumberCraft + is one millisecond.

3. Date and time related data structures

We can get the date and time through the tm structure in the standard C _ tm structure +. The tm structure is defined in time.h as follows:

# ifndef _ TM_DEFINED

Struct tm {

Int tm_sec; / * second-value range is [0BZ 59] * /

Int tm_min; / * score-value range is [0Jing 59] * /

The value range of int tm_hour; / * is [0Jing 23] * /

Int tm_mday; / * the date-value range of the month is [1c31] * /

Int tm_mon; / * month (starting from January, 0 represents January)-value range is [0mem11] * /

Int tm_year; / * year, which is equal to the actual year minus 1900 * /

The int tm_wday; / * week-value range is [0Magne6], where 0 represents Sunday, 1 represents Monday, and so on * /

Int tm_yday; / * days from January 1st of each year-value range is [0365], where 0 represents January 1, 1 represents January 2, and so on * /

Int tm_isdst; / * daylight saving time identifier, when daylight saving time is implemented, tm_isdst is positive. If daylight saving time is not implemented, the tm_isdst is 0; if you do not know the situation, tm_isdst () is negative. , /

}

# define _ TM_DEFINED

# endif

The ANSI C standard calls this time, which uses the tm structure, as broken-down time.

While calendar time (Calendar Time) is expressed by the time_t data type, the time expressed in time_t (calendar time) is the number of seconds from a point in time (for example, 00:00:00 on January 1, 1970) to this time. 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 definition of time_t * /

# endif

You may wonder: since time_t is actually a long integer, what if the number of seconds (that is, calendar time) from a point in time (usually 00:00:00 on January 1, 1970) to that point (that is, calendar time) exceeds the range of numbers that a long shaping can represent? For a value of the time_t data type, it represents a time no later than 19:14:07 on January 18, 2038. In order to represent a longer period of time, some compiler vendors have introduced 64-bit or more shaping numbers to save calendar time. For example, Microsoft uses the _ _ time64_t data type in Visual C++ to save the calendar time, and uses the _ time64 () function to obtain the calendar time (instead of using the 32-bit word time () function), so that it can save the time before 00:00:00 on January 1, 3001 (excluding this point in time).

In the timeh header file, we can also see some functions that take time_t as the parameter type or return value type:

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 provides two different functions to convert calendar time (an integer represented by time_t) into the usual time format tm, which displays the year, month, day, minute and second separately:

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 point in time (the value of the time_t object) in Microsoft C pictured + 7.0 is the number of seconds that have elapsed between 00:00:00 on December 31, 1899, and that point in time, while various other versions of Microsoft Cpicket + and all different versions of Visual C++ calculate the number of seconds elapsed between 00:00:00 on January 1, 1970 and that point in time.

4. Functions related to date and time and their applications

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

4.1 get Calendar time

We can get the calendar time (Calendar Time) through the time () function, which is based on:

Time_t time (time_t * timer)

If you have declared the parameter timer, you can return the current calendar time from the parameter timer, or you can return the current calendar time by returning a value, that is, the number of seconds from a point in time (for example, 00:00:00 on January 1st, 1970) to the present time. If the parameter is NUL, the function will return the current calendar time only through the return value, such as the following example to display the current calendar time:

# include "time.h"

# include "stdio.h"

Int main (void)

{

Struct tm * ptr

Time_t lt

Lt = time (NUL)

Printf ("The Calendar Time now is% DSPO", lt)

Return 0

}

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

The Calendar Time now is 1122707619

1122707619 of them is the calendar time when I run the program. The number of seconds from 00:00:00 on January 1, 1970 to this time.

4.2 date and time of acquisition

The date and time mentioned here are what we usually call year, month, day, hour, minute, second and so on. We already know from Section 2 that this information is stored in a structure called tm, so how do you save a calendar time as an object with a tm structure?

The functions that can be used are gmtime () and localtime (), whose prototypes are:

Struct tm * gmtime (const time_t * timer)

Struct tm * localtime (const time_t * timer)

The gmtime () function converts the calendar time into world standard time (Greenwich mean time) and returns a tm structure to save the time, while the localtime () function converts the calendar time into local time. For example, if the world standard time obtained by using the gmtime () function is 07:18:20 on July 30, 2005, then the local time I use the localtime () function in China will be 8 hours later than the world standard time, that is, 15:18:20 on July 30, 2005. Here is 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:% DPo", local- > tm_hour)

Local=gmtime & t

Printf ("UTC hour is:% DPo", local- > tm_hour)

Return 0

}

The result of the operation 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 return a string of type char*. The format of the time returned is:

What day of the week, month, date: minutes: seconds, years / nUnix 0

For example: Wed Jan 02 02:03:55 1980/n/0

Where / n is a newline character and / 0 is an empty character indicating the end of the string. Here are the prototypes of two functions:

Char * asctime (const struct tm * timeptr)

Char * ctime (const time_t * timer)

The asctime () function generates a string of time information with a fixed format through the tm structure, while ctime () generates a time string through the calendar time. In this case, the asctime () function just fills the fields in the tm structure object into the corresponding position of the time string, while the ctime () function needs to refer to the local time setting, convert the calendar time into 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 output of the two printf statements of the following program is different (unless you set the local time zone to the world standard time zone):

# 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

}

Running 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 into the format we want. Its prototype is as follows:

Size_t strftime (

Char * strDest

Size_t maxsize

Const char * format

Const struct tm * timeptr

);

According to the format command in format pointing string, we can put the time information saved in timeptr in the string pointed to by strDest, and store up to maxsize characters in strDest. This function returns the number of characters placed in the string pointed to strDest.

The operation of the function strftime () is somewhat similar to sprintf (): it identifies the collection of formatted commands starting with the percent sign (%), and the formatted output is placed in a string. The format command describes the exact representation of various date and time information in the string strDest. Other characters in the format string are placed in the string as is. Format commands are listed below, and they are case-sensitive.

Shorthand for% a day of the week

The full name of% A day of the week

Shorthand for% b month minutes

Full name of% B month

C time string of standard dates

The last two digits of% C year

The day ordinal of a month expressed in decimal system% d

% D month / day / year

% e is in a two-character field, the day ordinal of a month expressed in decimal system

% F year-month-day

The last two digits of the% g year, using week-based years

% G year, using week-based year

% h abbreviated month name

% H 24-hour hours

% I 12-hour hours

The day ordinal of a year expressed in% j decimal system

Month expressed in m decimal system

The number of minutes represented by the% M ten-hour system

% n New Line character

% p equivalent display of local AM or PM

% r 12 hours of time

% R displays hours and minutes: hh:mm

Seconds of% S decimal system

% t horizontal tabs

% T display minute and second: hh:mm:ss

% u the day ordinal of the week, Monday is the first day (values from 0 to 6, Monday is 0)

% U the week ordinal of the year, with Sunday as the first day (values from 0 to 53)

% V week ordinal of a year, using a week-based year

The day of the week in decimal% w (values from 0 to 6, 0 on Sunday)

The week ordinal of% W, with Monday as the first day (values from 0 to 53)

% x standard date string

% X standard time string

% y decimal year without century (values from 0 to 99)

The decimal year of the century part of the% Y belt

% zmine% Z time zone name, if the time zone name cannot be obtained, an empty character is returned.

%% sign

If you want to show what time it is, and display it on a 12-hour clock, like the following program:

# 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 is now I p", ptr)

Printf (str)

Return 0

}

The running results are as follows:

It is now 4PM

The following program displays the current full date:

# include

# include

Void main (void)

{

Struct tm * newtime

Char tmpbuf [128]

Time_t lt1

Time & lt1)

Newtime=localtime & lt1)

Strftime (tmpbuf, 128, "Today is% A, day% d of% B in the year% Y.Association", newtime)

Printf (tmpbuf)

}

Running result:

Today is Saturday, day 30 of July in the year 2005.

4.5 calculate the length of the duration

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

Double difftime (time_t time1, time_t time0)

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

# 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)); / /

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report