C++实现获取时间戳和计算运行时长
更新时间:2024年12月16日 08:44:13 作者:訫悦
这篇文章主要为大家详细介绍了如何使用C++实现获取时间戳和计算运行时长功能,文中的示例代码讲解详细,有需要的小伙伴可以参考一下
一、便于使用,使用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; }
运行结果:
到此这篇关于C++实现获取时间戳和计算运行时长的文章就介绍到这了,更多相关C++获取时间戳内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
最新评论