Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print milliseconds using format in C++20

I have the following code were I am struggling to get the declarative way of doing what I want.

I would like to have current time outputed up to ms precission(rounding down is also fine, e.g 129999 us can be rounded to 129ms, but I prefer 130 in this case).

note: I am using fmt since from what I see <format> header is still unimplemented.

#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";
}
like image 394
NoSenseEtAl Avatar asked Oct 23 '25 18:10

NoSenseEtAl


1 Answers

#include <fmt/chrono.h>

auto a = system_clock::now();
print("{:%FT%T%Oz}\n", a);
print("{0:%FT%H:%M:}{1:%S}{0:%Oz}\n", a,a.time_since_epoch());

prints

2021-04-13T21:38:04+0800
2021-04-13T21:38:04.076+0800
like image 62
Barrypp.zzx Avatar answered Oct 26 '25 08:10

Barrypp.zzx