1. Sometimes we need to calculate the execution time of the program. For example, if we want to analyze the algorithm time, we can use the following function.
Precise to us.
# Include <sys/time. h> int gettimeofday (struct timeval * TV, struct timezone * tz); strut timeval {long TV _sec;/* seconds */long TV _usec;/* microseconds */}; gettimeofday saves the time in the Structure TV. tz Is generally replaced by null. # include <sys/time. h <# include <stdio. h <# include <math. h <void function () {unsigned int I, j; Double Y; for (I = 0; I <1000; I ++) for (j = 0; j <1000; j ++) y = sin (double) I);} Main () {struct timeval tpstart, tpend; float timeuse; gettimeofday (& tpstart, null); function (); gettimeofday (& tpend, null); timeuse = 1000000 * (tpend. TV _sec-tpstart. TV _sec) + tpend. TV _usec-tpstart. TV _usec; timeuse // = 1000000; printf ("used time: % F \ n", timeuse); exit (0 );}
This program outputs the execution time of the function. We can use this to test the system performance or analyze the efficiency of the function algorithm. One output result on my machine is: used time: 0.556070.
2. The second is what I often use:
Before executing the program, add time, for example, input time./ABC, accurate to Ms.
3. clock function (accurate to 1/clocks_per_sec seconds, in milliseconds)
# Include <iostream>
# Include <ctime>
Using namespace STD;
Int max (int x, int y)
{
Return (x> Y )? X: Y;
}
Int main ()
{
Const double begin = clock ();
For (INT I = 10000; I> 0; I --)
For (Int J = 10000; j> 0; j --)
Max (I, j );
Const Double end =
Clock ();
Cout <begin <"" <end;
Return 0;
}