Based on the use of C and C++ time function

  • 2020-04-02 01:06:07
  • OfStack

C/C++ manipulation of time also has a lot to be noted. Recently, there are many users in the technology group also repeatedly asked the C++ language to the time of the operation, acquisition and display, and so on. Next, in this article, I will focus on the use of time and date in C/C++.
By learning many C/C++ libraries, you can have many ways to manipulate and use your time. But before you do that, you need to understand the concepts of "time" and "date." here are a few:
Coordinated Universal Time (UTC) : Coordinated universal Time, also known as world standard Time, is also known as Greenwich Mean Time (GMT). For example, the time difference between mainland China and UTC is + 8, which is UTC + 8. The United States is utc-5.
Calendar Time: Calendar time is the number of seconds elapsed from a standard time point to this time. The standard time point will be different for different compilers, but for a compilation system, the standard is the same point in time, the compilation system corresponding to the time in the calendar time are measured through the standard time, so the calendar time is "relative time", but no matter where you are a time zone, at the same time for the same standard time point, the calendar time is the same.
Epoch: point in time. The time point in standard C/C++ is an integer represented by the number of seconds (calendar time) between the time at that point and the standard time point.
Clock tick. Clock timing unit (not called clock ticks), the length of time a clock timing unit is controlled by the CPU. A clock tick is not a clock cycle of the CPU, but a basic unit of time in C/C++.
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, both in structure definition and naming, has a distinct C style. Next, I'll show you how to use the date time function in C/C++.
2. timing
The timing function in C/C++ 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 ticks between "start this program process" and "call clock() function in the program", which in MSDN is called wall clock time. Among them, clock_t is the data type used to save the time. In the time. H file, we can find its definition:


#ifndef _CLOCK_T_DEFINED
typedef long clock_t;
#define _CLOCK_T_DEFINED
#endif 

Clearly, 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 are in a second. It is defined as follows:
# define CLOCKS_PER_SEC (1000) (clock_t)
You can see that for every thousandth of a second (1 millisecond), the value returned by calling clock () is increments by 1. For example, you can use the formula clock()/CLOCKS_PER_SEC to calculate the running 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 to calculate how long it takes your machine to run a loop or process other events:

#include  " stdio.h " 
#include  " stdlib.h " 
#include  " time.h " 
int main( void )
{
    long     i = 10000000L;
    clock_t start, finish;
    double   duration;
    
    printf( "Time to do %ld empty loops is ", i );
    start = clock();
    while( i-- )       ;
    finish = clock();
    duration = (double)(finish - start) / CLOCKS_PER_SEC;
    printf( "%f secondsn", duration );
    system("pause");
}

On the author's machine, the results are as follows:
Time to do 10000000 empty loops is 0.03000 seconds
We saw above that the length of the clock timing unit is 1 millisecond, so the accuracy of timing is also 1 millisecond, so can we make the timing accuracy higher by changing the definition of CLOCKS_PER_SEC, by making it bigger? By trial and error, you'll find that it doesn't work. In standard C/C++, the smallest unit of time is one millisecond.
3. Date - and time-related data structures
In standard C/C++, we can get the date and time through tm structure, which is defined as follows in time.h:

#ifndef _TM_DEFINED
struct tm {
int tm_sec;      
int tm_min;      
int tm_hour;     
int tm_mday;     
int tm_mon;      
int tm_year;     
int tm_wday;     int tm_yday;     
int tm_isdst;    
};
#define _TM_DEFINED
#endif 

The ANSI C standard calls this time using a tm structure break-down time.
Calendar Time, on the other hand, is represented by the time_t data type, and the Time (Calendar Time) represented by time_t is the number of seconds from a point in Time (for example, 0:0:0, January 1, 1970) to that Time. In time.h, we can also see that time_t is a long integer:

#ifndef _TIME_T_DEFINED
typedef long time_t; 
#define _TIME_T_DEFINED       
#endif 

You might wonder: since time_t is actually a long integer, what if the number of seconds (calendar time) from a point in time (usually 0 o 'clock, 0 o 'clock, 0 minutes, 0 seconds on January 1, 1970) to that time (that is, the number of seconds) is beyond the range of Numbers that a long integer can represent? For a value of the time_t data type, it represents the time no later than 19:14:07 on January 18, 2038. To be able to represent longer periods of time, some compiler vendors have introduced 64-bit or even longer integers to hold calendar times. For example, Microsoft USES the _time64_t data type in Visual C++ to save the calendar time, and gets the calendar time by using the _time64 () function (instead of using the 32-bit word time () function), so that the time before 0 o 'clock, 0 minutes and 0 seconds (excluding the time point) on January 1, 3001 can be saved by this data type.
In the time.h header file, we can also see some functions that take time_t as 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 also provides two different functions to convert the calendar time (an integer represented by time_t) to the tm time format that we usually see that displays the time of year, month, day, minute and second separately:
Struct tm * gmtime(const time_t *timer);
Struct tm * localtime(const time_t * timer);
By looking at the MSDN, we can know the Microsoft C/C + + 7.0 point in time the value of the (time_t object value) from December 31, 1899 0 0 0 seconds to this point in time after the number of seconds, and various other versions of the Microsoft C/C + + and all different versions of Visual C + + is calculated from January 1, 1970 0 0 0 seconds to this point in time when the number of seconds.
4. Functions and applications related to date and time
In this section, I'll show you how to manipulate time using the function declared in time.h. These operations include taking the current time, calculating the interval, displaying the time in different forms, and so on.
4.1 get calendar time
We can get Calendar time by using the time() function, whose prototype is:
Time_t time (time_t * timer);
If you have declared a parameter timer, you can either return the current calendar time from the parameter timer or return the current calendar time by the return value, which is the number of seconds from a point in time (for example, 0 minutes 0 seconds on January 1, 1970) to the present time. If the argument is null (NUL), the function returns the current calendar time only by the return value, as shown in the following example:

#include "time.h"
#include "stdio.h"
int main(void)
{
     struct tm *ptr;
     time_t lt;
     lt =time(NUL);
     printf("The Calendar Time now is %dn",lt);
     return 0;
} 

The result of running is related to the time at that time. The result of my running is:
The Calendar Time now is 1122707619
Where 1122707619 is the calendar time when I run the program. The number of seconds from 0 minutes 0 seconds on January 1, 1970 to this time.
4.2 get the date and time
The date and time mentioned here is 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 named tm, so how do you save a calendar time as a tm structure object?
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 to world standard time(Greenwich mean time) and returns a tm structure to save the time, while the localtime() function converts the calendar time to localtime. For example, the world standard time obtained by using the gmtime () function is 7:18:20 seconds on July 30, 2005, so the localtime obtained in China by using the localtime () function will be 8 hours later than the world standard time, that is, 15:18:20 seconds on July 30, 2005. 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: %dn",local->tm_hour);
     local=gmtime(&t);
     printf("UTC hour is: %dn",local->tm_hour);
     return 0;
}
 The running result is: 
Local hour is: 15
UTC hour is: 7 

4.3 fixed time format
We can display the time in a fixed format using the asctime() and ctime() functions, both of which return a char* string. The time format returned is:
Week month date time: minutes: seconds year n\0
Example: Wed Jan 02 02:03:55 1980\n\0
Where \n is a newline character and \0 is a null character to indicate the end of the string. Here are the prototypes of the two functions:
Char * asctime(const struct tm * timeptr);
Char * ctime(const time_t *timer);
The asctime() function generates a fixed format of the stored time information string through a tm structure, while ctime() generates a time string through a calendar time. In this case, the asctime () function simply fills in the fields of the tm structured object in the corresponding position of the time string, while the ctime () function needs to first refer to the local time setting, convert the calendar time to the local time, and then regenerate the formatted string. Below, if t is a non-empty time_t variable, then:

printf(ctime(&t));
 Is equivalent to: 
struct tm *ptr;
ptr=localtime(&t);
printf(asctime(ptr)); 

So the two printf statements in this program output different results (unless you set your 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(<);
     printf(asctime(ptr));
     printf(ctime(<));
     return 0;
}
 Operation results: 
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 saved in timeptr in the string pointed to by strDest according to the format command in the pointing string, and store maxsize characters in strDest at most. This function returns the number of characters placed in the string pointed to by strDest.
The strftime() function does something similar to sprintf() : identifies a collection of format commands that start with a percent sign (%) and formats the output into a string. The format command describes the exact representation of various date and time information in the strDest string. The rest of the characters in the format string are put into the string as is. Format commands are listed below and are case sensitive.
A shorthand for the day of the week
A full name of the day of the week
%b months
Full name of month B
%c time series of standard dates
The last two digits of the year
%d represents the day of the month in decimal form
D months/days/years
%e is the day of the month in the two-character field, represented in decimal
F year - month - day
The last two digits of the %g year, using the week-based year
%G years, using week-based years
The name of the month in short
H 24-hour hours
%I 12 hour hours
%j decimal number of days of the year
The month represented by the decimal system %m
%M in ten - hour minutes
% n new line operator
%p local AM or PM equivalent display
R 12 hours
%R shows hours and minutes: hh:mm
%S in decimal seconds
%t horizontal TAB character
%T display minutes and seconds: hh:mm:ss
Day of the week, Monday is the first day (values from 0 to 6, Monday is 0)
Week of year, starting with Sunday (value 0 to 53)
%V weeks of the year, using week-based years
%w decimal day of the week (values 0 to 6, Sunday 0)
Week of the year, start with Monday (values from 0 to 53)
%x standard date string
%X standard time series
%y decimal year without century (values from 0 to 99)
%Y decimal year with century part
%z, %z time zone name, return null if the time zone name cannot be obtained.
% % percent
If you want to show what time it is and display it in a 12-hour format, like this:

#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 operation result is as follows: 
It is 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( <1 );
newtime=localtime(<1);
strftime( tmpbuf, 128, "Today is %A, day %d of %B in the year %Y.n", newtime);
printf(tmpbuf);
}
 Operation results: 
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 the typing speed. In section 1, timing, I gave an example using the clock function. The Clock() function can be accurate to milliseconds. We can also 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 interval in seconds returned by this function is of double type, this does not indicate that the time is as accurate as the double, as is assumed by its arguments (time_t is calculated in seconds). Take 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));//<-
     system("pause");
     return 0;
} 

The running result is:
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 coincidentally a full two seconds. In fact, you put "//" in the program above < - "replace the line of comment with the following line of code:
Printf ("The pause used %f seconds.\n",end-start);
The result is the same.
4.6 decompose time into calendar time
Here, the decomposition time is the time structure saved by the components of year, month, day, hour, minute, second, etc., which is tm structure in C/C++. 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. This allows us to set a breakdown time and then operate on that time. The following example can be used to calculate the day of the week on July 1, 1997:

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

Now notice, with the mktime() function, can we manipulate any time before now? Can you work out the day of the week of August 15, 1945 in this way? The answer is no. Because this is before January 1, 1970, in most compilers, such a program would compile but terminate at run time.


Related articles: