C language time. h clock () function test program running time method, time. hclock
The clock () function can be used to calculate the execution time of a program in C language.
_ Cribd clock_t _ cdecl _ MINGW_NOTHROW clock (void); (it can be regarded as clock_t clock (void );)
This function returns the number of CPU clock units (clock tick) between "enabling this program process" and "calling the clock () function in the program, 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 clock () function is increased by 1.
The following is an example:
# Include
# Include
# Include
Int main () {long I = 0000000l; clock_t start, finish; double TheTimes; printf ("the time required to do % ld null loop is", I ); start = clock (); while (I --); finish = clock (); TheTimes = (double) (finish-start)/CLOCKS_PER_SEC); printf ("% f seconds. \ N ", TheTimes); return 0 ;}
However, the result of each run is:
It takes 10000000 seconds to create 0.000000 null loops. Process returned 0 (0x0) execution time: 0.438 s Press any key to continue.
The number of cycles cannot be increased.
The final problem was found:
# Include
# Include
# Include
Int main () {long I = 0000000l; clock_t start, finish; double TheTimes; printf ("the time required to do % ld null loop is", I ); start = clock (); while (I --); finish = clock (); TheTimes = (double) (finish-start)/CLOCKS_PER_SEC; // red statement printf ("% f seconds. \ N ", TheTimes); return 0 ;}
Let's look at the difference between the red row and the above. Now I understand it! Because the brackets operator changes the operation priority, the four arithmetic operations in it are converted into division between integers, resulting in the loss of digits and errors.
It seems that the details are very important.
Write and share with you.