我是新手std::chrono
,我正在寻找一种简单的方法来构造一个string
包含格式为hhh:mm:ss的时间间隔(是的,三个小时的数字),以指示开始时间点与现在之间的时差。
我将如何使用steady_clock
?关于Cppreference的示例不太适合这个问题。
每当您发现自己在<chrono>
库中的各个单元之间手动应用转换因子时,都应该问自己:
为什么要手动转换单位?这不是
<chrono>
应该为我做的事吗?
“转换因子”是60或1000或100或任何其他值。如果您在代码中看到它,则表示您很容易遇到转换系数错误。
这是在没有这些转换因子的情况下重写的sasha.sochka的代码。为了说明这种技术的普遍程度,还为闪光添加了毫秒:
#include <chrono>
#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>
int main() {
using namespace std::chrono;
steady_clock::time_point start;
steady_clock::time_point now = steady_clock::now();
auto d = now -start;
auto hhh = duration_cast<hours>(d);
d -= hhh;
auto mm = duration_cast<minutes>(d);
d -= mm;
auto ss = duration_cast<seconds>(d);
d -= ss;
auto ms = duration_cast<milliseconds>(d);
std::ostringstream stream;
stream << std::setfill('0') << std::setw(3) << hhh.count() << ':' <<
std::setfill('0') << std::setw(2) << mm.count() << ':' <<
std::setfill('0') << std::setw(2) << ss.count() << '.' <<
std::setfill('0') << std::setw(3) << ms.count();
std::string result = stream.str();
std::cout << result << '\n';
}
还有其他方法可以在不暴露转换因子的情况下进行操作,这种方法仅是示例。我的主要观点是:避免在代码中对单位转换因子进行硬编码。它们容易出错。即使您第一次进行编码时正确无误,转换因子也很容易受到将来代码维护的影响。您可以要求所有单位转换都在<chrono>
库中进行,从而对代码进行将来的验证。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句