Use the functions in the C Runtime Library, so it has platform portability.
Include header file: Time. h
# Include <time. h>
Function introduction:
1. Clock ()
Function:
Returns the time taken by the processor to call a process or function.
Function prototype:
Clock_t clock (void );
Return Value:
If the process is successful, the number of CPU tick messages returned from the execution of the process to the time when clock () is called (clock_t is a long integer) is returned)
-1 is returned if the request fails;
Note: To convert clock_t to seconds or milliseconds, divide it by clocks_per_secclk_tck or clk_tck (name earlier than 6.0)
In the time. h file, a constant clocks_per_sec is also defined to indicate the number of clock time units in a second. Its definition is as follows:
# Define clocks_per_sec (clock_t) 1000)
2. difftime ()
Function:
Returns the time interval between two time_t variables, that is, the time difference between two time points.
Function prototype:
Double difftime (time_t Timer1, Time_t
Timer0 );
Parameters:
Timer1: End Time
Timer0: Start Time
Return Value:
Double-precision floating point value
Note: Both clock_t and time_t are unsigned long values, but one represents milliseconds and the other represents seconds.
Example:
# Include <time. h> # include <stdio. h> # include <stdlib. h> void main () {time_t c_start, t_start, c_end, t_end; c_start = clock (); t_start = Time (null ); // used to pause system ("pause"); c_end = clock (); t_end = Time (null); printf ("the pause used % f ms by time (). \ n ", difftime (c_end, c_start); printf (" the pause used % f s by clock (). \ n ", difftime (t_end, t_start ));}
Output result:
The pause used 12203.000000 MS by time ().
The pause used 13.000000 s by clock ().