很多时候我们需要计算某段代码操作所耗费时间我们往
往会这样写:
第种情况精确到毫秒
clock_t start = null, end = null;
double duration = 0;
start = clock;
// operation statements here
end = clock;
duration = (double) (end - start)/CLOCK_PER_SEC;
第 2中情况精确到秒
time_t start = null, end = null;
duration = 0;
start = time(NULL);
// operation statements here
end = time(NULL);
duration = end - start;
为了是这些计时代码能够在C工程中重用我们可以对其进行封装
利用对象作用域来计算时间当然这些类只能用在某些特定场合
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;
}
TimeCost2
{
public:
TimeCost2{ m_cur = clock;}
~TimeCost2
{
clock_t cur = clock;
double cost = (double)(cur - m_cur)/CLOCK_PER_SEC;
prf("Time cost: %f s \n", cost);
}
private:
clock_t m_cur;
}
当然这两个类最大缺陷就是时间计算严格依赖于对象生存期
最新评论