灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:4115回复:0

一个计时器的实现C/C++

楼主#
更多 发布于:2011-11-20 10:15
直接上代码
定义头文件:

//: C09:Cpptime.h
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// A simple time class
#ifndef CPPTIME_H
#define CPPTIME_H
#include <ctime>
#include <cstring>

class Time {
   time_t t;
   tm local;
   char asciiRep[26];
   unsigned char lflag, aflag;
   void updateLocal() {
       if(!lflag) {
           local = *localtime(;t);
           lflag++;
       }
   }
   void updateAscii() {
       if(!aflag) {
           updateLocal();
           strcpy(asciiRep,asctime(;local));
           aflag++;
       }
   }
public:
   Time() { mark(); }
   void mark() {
       lflag = aflag = 0;
       time(;t);
   }
   const char* ascii() {
       updateAscii();
       return asciiRep;
   }
   // Difference in seconds:
   int delta(Time* dt) const {
       return int(difftime(t, dt->t));
   }
   int daylightSavings() {
       updateLocal();
       return local.tm_isdst;
   }
   int dayOfYear() { // Since January 1
       updateLocal();
       return local.tm_yday;
   }
   int dayOfWeek() { // Since Sunday
       updateLocal();
       return local.tm_wday;
   }
   int since1900() { // Years since 1900
       updateLocal();
       return local.tm_year;
   }
   int month() { // Since January
       updateLocal();
       return local.tm_mon;
   }
   int dayOfMonth() {
       updateLocal();
       return local.tm_mday;
   }
   int hour() { // Since midnight, 24-hour clock
       updateLocal();
       return local.tm_hour;
   }
   int minute() {
       updateLocal();
       return local.tm_min;
   }
   int second() {
       updateLocal();
       return local.tm_sec;
   }
};
#endif // CPPTIME_H ///:~
使用示例:

//: C09:Cpptime.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Testing a simple time class
#include "head.h"
#include <iostream>
using namespace std;

int main() {
   Time start;
   for(int i = 1; i < 1000; i++) {
       cout << i << ' ';
       if(i%10 == 0) cout << endl;
   }
   Time end;
   cout << endl;
   cout << "start = " << start.ascii();
   cout << "end = " << end.ascii();
   cout << "delta = " << end.delta(;start);
} ///:~  

喜欢0 评分0
游客

返回顶部