C\C++语言中的计时函数

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; 
} 





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值