【发布时间】:2020-12-28 22:03:57
【问题描述】:
我有以下code,如果我正在努力获得声明式的方式来做我想做的事。
我希望将当前时间输出到 ms 精度(向下舍入也可以,例如 129999 我们可以舍入到 129ms,但在这种情况下我更喜欢 130)。
注意:我正在使用 fmt,因为我看到 <format> 标头仍未实现。
#include<string>
#include<chrono>
#include<iostream>
#include<thread>
#include<fmt/format.h>
#include<fmt/chrono.h>
using namespace std::chrono;
int main(){
for (int i =0; i<5;++i){
// I wish this was local_time, not sys time, and that sys_time<milliseconds> worked
const std::chrono::sys_time<nanoseconds> now =
(std::chrono::system_clock::now());
auto round_now = std::chrono::round<milliseconds>(now);
int64_t ms = (round_now.time_since_epoch()%seconds(1)).count();
// %S does not print milliseconds
std::cout << fmt::format("{:%F %H:%M:%S}.{:03}", now, ms) << std::endl;
std::cout << std::endl;
std::this_thread::sleep_for(milliseconds(100));
}
std::cout << "Bye";
}
【问题讨论】:
-
您提供的代码有什么问题?它不打印毫秒吗?
-
你能举个例子说明你得到的输出,以及你想要的输出吗?
-
就像我说的那样,我想要一种声明性的方式来做这件事,而不是我手动计算秒的毫秒部分。