方法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;
}
不要糾結於爲什麼兩個時間上有差異,即便是人寫兩次一樣的程序也不能保證時間上完全一樣。