计算机二级C++系统相关:有用的计时的类
来源:优易学  2010-1-14 11:40:00   【优易学:中国教育考试门户网】   资料下载   IT书店
  很多时候,我们需要计算某段代码的操作所耗费的时间,我们往往会这样写:
  第一种情况,精确到毫秒。
  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;
  为了是这些计时的代码能够在C++工程中重用,我们可以对其进行封装。
  利用对象的作用域来计算时间。当然这些类只能用在某些特定的场合。
  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;
  }
  当然,这两个类的最大缺陷就是时间的计算严格的依赖于对象的生存期。

责任编辑:cyth

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训