1. Use the clock () function
Header file:
Clock () function that returns "the number of timer units (clock tick) for the CPU clock from the start of the program to the call to this function"
Every 1ms, Count value +1
Precision: 1 ms
#include
#include
int main ()
{
clock_t Start,end; typedef long CLOCK_T
start = Clock ();
Long i= 1000000000l;while (i--) {}
end = Clock ();
#define CLOCKS_PER_SEC ((clock_t) 1000)
Double duration = (double) (End-start)/clocks_per_sec;
printf ("%f\n", duration); 4.015
return 0;
}
2. Use the time () function
Header file:
Clock () returns the number of seconds that have elapsed since the year 1970.01.01 0:0:0 seconds.
Calendar Time
Accuracy: 1 seconds
#include
int main ()
{
time_t start,end; typedef long time_t;
Start = time (NULL); Equivalent to time (&start);
Long I=1000000000l;while (i--) {}
End = Time (NULL);
Long duration =end-start;
printf ("%ld\n", duration); 4
return 0;
}
3. Use the GetTickCount () function
Header file:
In the case of high precision, you can take advantage of the GetTickCount () function, which returns a DWORD that represents the time interval (maximum 49.7 days) experienced by the computer after startup in Ms. In a shorter timing of the timing error of 15ms, in a longer time, the timing error is low, if the timing is too long, as if the crash, CPU occupancy rate is very high, can only be used for the delay of the program is not high.
Accuracy: 1 ms, short time error 15ms
#include
#include
int main ()
{
DWORD Start,end;//typedef unsigned long DWORD;
Start = GetTickCount ();
Long I=1000000000l;while (i--) {}
End = GetTickCount ();
Double duration = (double) (End-start)/1000;
printf ("%f\n", duration); 3.922
return 0;
}
4. Use the Queryfrequencycount () function
Header file:
High Precision Counters
Accuracy: 1 microseconds, error no more than 0.5 subtle (precision is 1000 000/(CPU frequency) microseconds)
#include
#include
int main ()
{
Large_integer F;
QueryPerformanceFrequency (&f)//Get internal high-precision counter frequency
Double dfreq;
Dfreq = (double) F.quadpart; Get the frequency of the counter
Large_integer Start,end;
QueryPerformanceCounter (&start); Gets the current count value of the internal high-precision counter
Long I=1000000000l;while (i--) {}
QueryPerformanceCounter (&end);
Time difference = count value/frequency (unit s)
Double duration = (double) (end. Quadpart-start.quadpart)/dfreq;
printf ("%f\n", duration);//3.969499
return 0;
}