一、便于使用,使用chrono封装一个简单的类
#pragma once
#include <chrono>
using CTime_point = std::chrono::high_resolution_clock::time_point;
class CElapsedTime final
{
public:
static CTime_point now() {
return std::chrono::high_resolution_clock::now();
}
using s = std::chrono::seconds;
using ms = std::chrono::milliseconds;
using us = std::chrono::microseconds;
using ns = std::chrono::nanoseconds;
//获取当前时间戳 类型: s/ms/us/ns
template<typename T = CElapsedTime::ms> static long long since_epoch() {
const auto now = std::chrono::system_clock::now();//时间戳要用 system_clock
const auto sinceEpoch = std::chrono::duration_cast<T>(now.time_since_epoch());
return sinceEpoch.count();
}
//计算时间差 类型: s/ms/us/ns
template<typename T = CElapsedTime::ms>
static long long duration(const CTime_point &begin, const CTime_point &end)
{
const auto delta = std::chrono::duration_cast<T>(end - begin);
return delta.count();
}
const static long long _s = 1;
const static long long _ms = 1000;
const static long long _us = 1000000;
const static long long _ns = 1000000000;
//计算时间差 返回浮点类型
template<size_t T = CElapsedTime::_ms>
static double duration(const CTime_point &begin, const CTime_point &end)
{
const std::chrono::duration<double, std::ratio<1, T>> delta = end - begin;
return delta.count();
}
};
二、直接调用
#include <stdlib.h>
#include <thread>
#include <iostream>
#include <iomanip>
#include "CElapsedTime.h"
int main(int argc, char *argv[])
{
#ifdef _WIN32
_tzset();
_putenv("_tz=GMT +8");
#else
setenv("TZ", "Asia/Shanghai", 1);
#endif
auto begin = CElapsedTime::now();
std::this_thread::sleep_for(std::chrono::milliseconds(1230));//运行时长
auto end = CElapsedTime::now();
long long sinceEpoch = CElapsedTime::since_epoch();
std::cout << "since epoch: " << sinceEpoch << std::endl;
std::cout << "run(s): " << CElapsedTime::duration<CElapsedTime::s>(begin, end) << std::endl;
std::cout << "run(ms): " << CElapsedTime::duration<CElapsedTime::ms>(begin, end) << std::endl;
std::cout << "run(us): " << CElapsedTime::duration<CElapsedTime::us>(begin, end) << std::endl;
std::cout << "run(ns): " << CElapsedTime::duration<CElapsedTime::ns>(begin, end) << std::endl;
std::cout << "run(s): " << std::fixed << std::setprecision(3) << CElapsedTime::duration<CElapsedTime::_s>(begin, end) << std::endl;
std::cout << "run(ms): " << std::fixed << std::setprecision(3) << CElapsedTime::duration<CElapsedTime::_ms>(begin, end) << std::endl;
std::cout << "run(us): " << std::fixed << std::setprecision(3) << CElapsedTime::duration<CElapsedTime::_us>(begin, end) << std::endl;
std::cout << "run(ns): " << std::fixed << std::setprecision(3) << CElapsedTime::duration<CElapsedTime::_ns>(begin, end) << std::endl;
return 0;
}
运行结果: