C语言显示程序运行时间并验证

软件:Dev C++

#include<stdio.h>
#include <Windows.h>
int main()
{
	double run_time;
	LARGE_INTEGER time_start;	//开始时间
	LARGE_INTEGER time_over;	//结束时间
	double dqFreq;		//计时器频率
	LARGE_INTEGER f;	
	QueryPerformanceFrequency(&f);
	dqFreq=(double)f.QuadPart;
	QueryPerformanceCounter(&time_start);	//计时开始
	/**需要计算运行时间的代码放这里**/
	
	/******************************/
	QueryPerformanceCounter(&time_over);	//计时结束
	run_time=1000000*(time_over.QuadPart-time_start.QuadPart)/dqFreq;
	//乘以1000000把单位由秒化为微秒,精度为1000 000/(cpu主频)微秒
	printf("\nrun_time:%fus\n",run_time);//这行显示运行时间
	return 0;
}

验证如下:
思路:通过time.h库文件中的gmtime获取当前秒数,并开始计时,当2秒过后结束计时,观察run_time和程序运行时间。

#include<stdio.h>
#include <windows.h>
#include <time.h>
int main()
{
	int k;
	time_t timep;
	struct tm *p;
	double run_time;
	LARGE_INTEGER time_start;	//开始时间
	LARGE_INTEGER time_over;	//结束时间
	double dqFreq;		//计时器频率
	LARGE_INTEGER f;	
	QueryPerformanceFrequency(&f);
	dqFreq=(double)f.QuadPart;
	time(&timep);
	p=gmtime(&timep);
	printf("当前系统:%d秒\n",p->tm_sec);//不一定正好在整数秒
	k=p->tm_sec+2; 
	printf("跳转至%d秒\n",k);
	QueryPerformanceCounter(&time_start);	//计时开始
	while(k!=p->tm_sec)
	{
		time(&timep);
		p=gmtime(&timep);
	}
	QueryPerformanceCounter(&time_over);	//计时结束
	run_time=1000000*(time_over.QuadPart-time_start.QuadPart)/dqFreq;
	printf("\nrun_time:%fus\n",run_time);
	return 0;
}
结果显示

在这里插入图片描述
run_time表示计时结束与计时开始的差,单位为毫秒;
Process exited after 1.836 seconds 表示整个程序运行了1.836秒;
两者基本吻合,验证成功。

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值