在 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++相关学习资料哦!