1. <time.h>中函数clock(),返回类型clock_t,精确度,毫秒级别
<span style="font-size:18px;">#include <stdio.h>
#include <time.h>
#include <math.h>
void test()
{
int i = 0;
int j = 0;
double a = 0;
while (i++ < 1000000)
while (j++ < 1000000)
{
a = sqrt(2.0);
}
}
int main(void)
{
clock_t start, finish;
double duration = 0.0;
start = clock();
test();
finish = clock();
duration = (double)(finish - start); //输出单位ms
duration = (double)(finish - start) / CLOCKS_PER_SEC; //输出单位为s, //#define CLOCKS_PER_SEC 1000
printf("%f seconds\n", duration);
return 0;
} </span>
2. 最精确的计时:QueryPerformanceCounter来查询定时器的计数值,如果硬件里有定时器,它就会启动这个定时器,并且不断获取定时器的值,这样的定时器精度,就跟硬件时钟的晶振一样精确的。
#include <stdio.h> #include <stdlib.h> #include <windows.h> #include <math.h> void test() { int i = 0; int j = 0; double a = 0; while (i++ < 1000000) while (j++ < 1000000) { a = sqrt(2.0); } } int main(void) { LARGE_INTEGER start; LARGE_INTEGER end; LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&start); test(); QueryPerformanceCounter(&end); printf("user time : %.10f seconds\n", (double)(end.QuadPart - start.QuadPart) / (double)freq.QuadPart); return 0; }
3. <time.h>中函数time(&t),精确度,秒级别 功能:取以秒为单位的,从1970年1月1日格林威治时间00:00:00算起的当前时间,并把它存在长整形变量t中,函数返回如前所述的时间秒值。
#include <stdio.h> #include <time.h> #include <dos.h> #include <conio.h> #include <windows.h> int main() { time_t t; time(&t); printf("Today's date and time: %s",ctime(&t)); time_t first, second; first=time(NULL); Sleep(2000); second=time(NULL); printf("The difference is: %f seconds",difftime(second,first)); getch(); return 0; }