如何解决C ++打印chrono :: duration的天,小时,分钟等
// #includes for <chrono>,<iostream>,etc.
using namespace std;
using namespace chrono;
int main(int argc,char* argv[]) {
auto sysstart = system_clock::Now();
LogInit(); // Opens a log file for reading/writing
// Last shutdown time log entry is marked by a preceding null byte
logFile.ignore(numeric_limits<streamsize>::max(),'\0');
if (logFile.fail() || logFile.bad()) {
// Calls GetLastError() and logs the error code and message
LogError("main");
}
// Parse the timestamp at the start of the shutdown log entry
tm end = { 0 };
logFile >> get_time(&end,"[%d-%m-%Y %T");
if (logFile.fail() || logFile.bad()) {
// Same as above. Param is name of function within which error occurred
LogError("main");
}
// Finally,we have the last shutdown time as a chrono::time_point
auto sysEnd = system_clock::from_time_t(mktime(&end));
// Calculate the time for which the system was inactive
auto sysInactive = sysstart - sysEnd;
auto hrs = duration_cast<hours>(sysInactive).count();
auto mins = duration_cast<minutes>(sysInactive).count() - hrs * 60;
auto secs = duration_cast<seconds>(sysInactive).count() - (hrs * 3600) - mins * 60;
auto ms = duration_cast<milliseconds>(sysInactive).count() - (hrs * 3600000)
- (mins * 60000) - secs * 1000;
return 0;
}
它可以工作,但是很难看,而且太冗长了。 仅使用STL函数执行此操作的更简单方法? MTIA:-)
编辑:我意识到,按照@ idclev463035818的注释,完整的代码毕竟不是那么复杂,我已经添加了缺少的内容。
解决方法
当您无法使用fmtlib或等待C ++ 20 <format>
时,您至少想尽可能地延迟cout()
的调用。另外,让<chrono>
为您处理计算。两种措施都可以改善摘要的简洁性:
const auto hrs = duration_cast<hours>(sysInactive);
const auto mins = duration_cast<minutes>(sysInactive - hrs);
const auto secs = duration_cast<seconds>(sysInactive - hrs - mins);
const auto ms = duration_cast<milliseconds>(sysInactive - hrs - secs);
输出:
cout << "System inactive for " << hrs.count() <<
":" << mins.count() <<
":" << secs.count() <<
"." << ms.count() << endl;
请注意,您还可以定义实用程序模板,
template <class Rep,std::intmax_t num,std::intmax_t denom>
auto chronoBurst(std::chrono::duration<Rep,std::ratio<num,denom>> d)
{
const auto hrs = duration_cast<hours>(d);
const auto mins = duration_cast<minutes>(d - hrs);
const auto secs = duration_cast<seconds>(d - hrs - mins);
const auto ms = duration_cast<milliseconds>(d - hrs - secs);
return std::make_tuple(hrs,mins,secs,ms);
}
结合结构化绑定具有很好的用例:
const auto [hrs,ms] = chronoBurst(sysInactive);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。