C语言计时函数
(2012-05-16 09:30:18)
标签:
杂谈 |
分类: c*cpp |
1. <time.h>中函数clock(),返回类型clock_t,精确度,毫秒级别
实例:
实例:
#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; //输出单位为妙,精确到毫秒级
//#define CLOCKS_PER_SEC 1000
printf("%f seconds\n", duration);
return 0;
}
2、<time.h>中函数time(&t),精确度,秒级别
功能:取以秒为单位的,从1970年1月1日格林威治时间00:00:00算起的当前时间,并把它存在长整形变量t中,函数返回如前所述的时间秒值。
测试程序如下:
#include"stdio.h "
#include"time.h "
#include"stdlib.h "
main()
{
long start,end;
time(&start);
delay(50000);
time(&end);
printf( "end-start=%ld\n ",end-start);
getch();
}QueryPerformanceCounter来查询定时器的计数值,如果硬件里有定时器,它就会启动这个定时器,并且不断获取定时器的值,这样的定时器精度,就跟硬件时钟的晶振一样精确的。
3. 最精确的计时:
#include <stdio.h>
#include <stdlib.h>
#include <windows.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;
QueryPerformanceFrequenc y(&freq);
QueryPerformanceCounter(&start);
test();
QueryPerformanceCounter(&end);
printf("user time : %.10f seconds\n", (double)(end.QuadPart - start.QuadPart) / (double)freq.QuadPart);
return 0;
}