In the C ++ programming language, there are many specific function applications that can help us implement many different specific functions and facilitate the actual development of programmers. For example, the C ++ clock () function mainly helps us implement the timing function. The related 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 timer units clock tick between "enabling this program process" and "calling the C ++ clock () function in the program, in MSDN, it is called the wall clock time wal-clock ). 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
Clock_t is a long integer. In the time. h file, a constant CLOCKS_PER_SEC is also defined to indicate the number of clock units in one second. Its definition is as follows:
- #define CLOCKS_PER_SEC ((clock_t)1000)
We can see that every 1‰ seconds, 1 millisecond), the value returned by calling the C ++ clock () function is increased by 1. For example, you can use the formula clock ()/CLOCKS_PER_SEC to calculate the running time of a process:
- 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 much time your machine spends running a loop or processing other events:
- # Include "stdio. h"
- # Include "stdlib. h"
- # Include "time. h"
- Int main (void)
- {
- Long I = 0000000l;
- Clock_t start, finish;
- Double duration;
- /* Measure the duration of an event */
- Printf ("Time to do % 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 running result is as follows:
- Time to do 10000000 empty loops is 0.03000 seconds
The preceding section describes the application of the C ++ clock () function. We can see that the length of the clock timing unit is 1 millisecond, and the timing accuracy is also 1 millisecond. Can we change the definition of CLOCKS_PER_SEC and define it as larger, so that the timing accuracy is higher? By trying, you will find that this is not the case. In standard C/C ++, the minimum unit of time is one millisecond.