主要时间类型
std::ratio 定义分式
std::ratio<60, 1> minutes;
std::ratio<60 * 60> hource;
std::ratio<1, 1000> milliseconds;
chrono命名空间定义好的时间单位
typedef duration <Rep, ratio<3600,1>> hours;
typedef duration <Rep, ratio<60,1>> minutes;
typedef duration <Rep, ratio<1,1>> seconds;
typedef duration <Rep, ratio<1,1000>> milliseconds;
typedef duration <Rep, ratio<1,1000000>> microseconds;
typedef duration <Rep, ratio<1,1000000000>> nanoseconds;
chrono::minutes mintu{2};
chrono::seconds sec{3};
chrono::milliseconds mills{500};
auto dul = sec - mills;
dul.count();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
- chrono::duration_cast<>() 时间单位转换
chrono::duration_cast<chrono::seconds>(mintu).count();
获取当前时间
time_point 表示一个时间点
chrono::system_clock::time_point now = chrono::system_clock::now();
std::time_t oldTime = time(nullptr);
cout << "oldTime = " << oldTime << endl;
chrono::system_clock::time_point timePoint = chrono::system_clock::now();
std::time_t newTime = chrono::system_clock::to_time_t(timePoint);
cout<<"newTime = " << newTime <<endl;
std::time_t nowTime = chrono::system_clock::to_time_t(now);
std::put_time(std::localtime(&nowTime), "%Y-%m-%d %X");
- std::localtime非线程安全,使用localtime_r函数代替
struct tm cutTm = {0};
std::put_time(localtime_r(&nowTime, &cutTm), "%Y-%m-%d %X");
打印程序执行耗时
class SpendTime
{
public:
SpendTime():_curTimePoint(std::chrono::steady_clock::now())
{
}
~SpendTime(){
auto curTime = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(curTime - _curTimePoint);
cout<<"SpendTime = "<< duration.count() <<"ms"<<endl;
}
private:
std::chrono::steady_clock::time_point _curTimePoint;
};
#include
#include
class Timer
{
public:
Timer() : _startTime(std::clock())
{
}
void Restart()
{
_startTime = std::clock();
}
double Elapsed() const
{
return double(std::clock() - _startTime) / CLOCKS_PER_SEC;
}
double ElapsedMin() const
{
return double(1) / double(CLOCKS_PER_SEC);
}
double ElapsedMax() const
{
return (double(std::numeric_limits<std::clock_t>::max()) - double(_startTime) / double(CLOCKS_PER_SEC));
}
private:
std::clock_t _startTime;
};
判断时间戳是否为当天
#include
#include
#include
#include
#include
#include
int checkTimestamp(const std::time_t timeStamp)
{
static std::time_t sLastTimestamp = 0;
if (sLastTimestamp == 0) {
static std::once_flag oc;
std::call_once(oc, [&]()
{
tzset();
sLastTimestamp = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
});
}
const int lastDay = (sLastTimestamp - timezone)/86400;
const int curDay = (timeStamp - timezone)/86400;
sLastTimestamp = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
return (curDay - lastDay);
}