我有以下code,我正在努力获取声明性方式来做自己想要的事情。
我想将当前时间输出到ms精度(四舍五入也很好,例如129999 us可以四舍五入为129ms,但在这种情况下我更喜欢130)。
注意:我正在使用fmt,因为从我看到的<format>
header 来看,它仍未实现。
#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";
}
最佳答案
%S
默认情况下显示毫秒。例如:
#include <fmt/chrono.h>
int main() {
fmt::print("{:%S}", std::chrono::system_clock::now().time_since_epoch());
}
打印(实际输出取决于当前时间):34.459
Godbolt:https://godbolt.org/z/Y1jzv5
关于c++ - 如何在C++ 20中使用格式打印毫秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63829143/