方法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;
}
不要纠结于为什么两个时间上有差异,即便是人写两次一样的程序也不能保证时间上完全一样。