程序运行时间

方法1:首先要用到clock函数在调用是需要知道函数原型clock_t clock ( void )”;其返回值“clock_t”为“long int”型(int存储的整数的值域小于long int,虽然他们在32位机器上都占用4个字节)

这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,其中clock_t是用来保存时间的数据类型,在time.h文件中对它的定义:
#ifndef _CLOCK_T_DEFINED
typedef long clock_t;
#define _CLOCK_T_DEFINED
#endif
clock_t是一个长整形数。在time.h文件中,还定义了一个常量CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元,另外在宏里(将"CLOCKS_PER_SEC"定义为"CLK_TCK")其定义如下: 
#define CLOCKS_PER_SEC  1000
可以看到每过千分之一秒(1毫秒),调用clock()函数返回的值就加1。
为了将其单位转换为秒需要:
((float)t/ CLOCKS_PER_SEC)

#include<iostream>
#include<ctime>
using namespace std;
class CTimer
{
public:
	CTimer()
	{
		cout << "CTimer()" << endl;
		_start = clock();

	}
	~CTimer()
	{
		cout << "~CTimer()" << endl;
		int a = 100000000;
		while (a--){}
		_end = clock();

		cout << ((float(_end - _start)) / CLOCKS_PER_SEC) << "s" << endl;
	}
public:
	clock_t _start;
	clock_t _end;
};
int main()
{
	CTimer* p= new CTimer;
	delete p;
	system("pause");
	return 0;
}


这就测试了100000000次循环的时间。

方法二:

#include<iostream>
#include<ctime>
using namespace std;
void FunTest()
{
	int a = 100000000;
	while (a--){}
}
int main()
{
	clock_t _start, _end;
	_start = clock();
	FunTest();
	_end = clock();
	cout << ((float(_end - _start)) / CLOCKS_PER_SEC) << "s" << endl;
	system("pause");
	return 0;
}


不要纠结于为什么两个时间上有差异,即便是人写两次一样的程序也不能保证时间上完全一样。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值