C++实现Timer时间类

    在 C/C++中,获取系统时间通常使用C的结构体来实现,使用起来相对不是很方便。而在使用等待函数的时候,windows和linux下使用的头文件和函数都不相同,等待的时间单位也不同(windows下为毫秒 linux下为微秒和秒)。

    为了方便使用,我将这些功能封装成了Timer类。

实现代码如下(Timer.hpp):

#pragma once
//判断操作系统
#ifdef _WIN32
#pragma warning(disable:4996)
#include <windows.h>
#elif __linux__
#include <unistd.h>
#endif
//时间和字符串头文件
#include <time.h>
#include <string>

typedef unsigned int uint;

class Timer {

public:

    struct{
        uint year;
        uint mon;
        uint day;
        uint hour;
        uint min;
        uint sec;
    };
    //程序等待(单位:毫秒)
    void wait(uint ms) {
    #ifdef _WIN32
        Sleep(ms);
    #elif __linux__
        usleep(ms * 1000);
    #endif
    }
    //程序开始的计时
    void start() {
        clocks=clock();
    };
    //程序结束的计时 返回消耗时间
    uint end() {
        return clock()-clocks;
    };
    //获取系统当前时间
    void getTime(){
        time(&rawtime);
        ptminfo = localtime(&rawtime);

        year = ptminfo->tm_year + 1900;
        mon = ptminfo->tm_mon + 1;
        day = ptminfo->tm_mday;
        hour = ptminfo->tm_hour;
        min = ptminfo->tm_min;
        sec = ptminfo->tm_sec;
    }
    //获取当前时间 返回字符串类型
    std::string getTimeStr() {
        getTime();
        return std::to_string(year) + "_" + std::to_string(mon) + "_" + std::to_string(day) + " "
            + std::to_string(hour) + ":" + std::to_string(min) + ":" + std::to_string(sec);
    }

private:
    //时间相关结构体
    clock_t clocks;
    time_t rawtime;
    tm* ptminfo;
};

使用方法如下:

//头文件
#include <iostream>
#include "Timer.hpp"
//使用std名字空间
using namespace std;
//主函数
int main()
{

    Timer timer;
    //获取系统当前时间
    timer.getTime();
    //取出并打印当前时间
    std::string str= to_string(timer.year) + "_" + to_string(timer.mon) + "_" + to_string(timer.day) + " "
        + to_string(timer.hour) + ":" + std::to_string(timer.min) + ":" + to_string(timer.sec);
    cout << str << endl;
    //获取当前时间的string并打印
    cout << timer.getTimeStr() << endl;
    //等待1000毫秒并打印等待时间
    timer.start();
    timer.wait(1000);
    cout << timer.end() << endl;
    //防止程序自动结束
    getchar();
    return 0;
}

打印结果:

关注微信公众号:  笑马编程  后台发送:C++资料,

即可领取C++相关学习资料哦!

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值