很多時(shí)候,我們需要計(jì)算某段代碼的操作所耗費(fèi)的時(shí)間,我們往往會(huì)這樣寫(xiě):
第一種情況,精確到毫秒。
clock_t start = null, end = null;
double duration = 0;
start = clock();
// operation statements here
end = clock();
duration = (double) (end - start)/CLOCK_PER_SEC;
第二中情況,精確到秒。
time_t start = null, end = null;
int duration = 0;
start = time(NULL);
// operation statements here
end = time(NULL);
duration = end - start;
為了是這些計(jì)時(shí)的代碼能夠在C++工程中重用,我們可以對(duì)其進(jìn)行封裝。
利用對(duì)象的作用域來(lái)計(jì)算時(shí)間。當(dāng)然這些類(lèi)只能用在某些特定的場(chǎng)合。
class TimeCost
{
public:
TimeCost(){ m_cur = time(NULL);
~TimeCost()
{
time_t cur = time(NULL);
prinftf("Time cost is %d s\n",cur - m_cur;
}
private:
time_t m_cur;
}
class TimeCost2
{
public:
TimeCost2(){ m_cur = clock();}
~TimeCost2()
{
clock_t cur = clock();
double cost = (double)(cur - m_cur)/CLOCK_PER_SEC;
printf("Time cost: %f s \n", cost);
}
private:
clock_t m_cur;
}
當(dāng)然,這兩個(gè)類(lèi)的最缺陷就是時(shí)間的計(jì)算嚴(yán)格的依賴(lài)于對(duì)象的生存期。