天天动画片 > 八卦谈 > C++实现Timer时间类

C++实现Timer时间类

八卦谈 佚名 2024-02-18 06:29:18

    在 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++


本文标题:C++实现Timer时间类 - 八卦谈
本文地址:www.ttdhp.com/article/48589.html

天天动画片声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
扫码关注我们