How to get higher precision (fractions of a second) in a printout of current time?
c++, time
Solution
You can do the following:
#include <chrono>
#include <ctime>
#include <iostream>
#include <string>
std::string GetLocalTime() {
auto now(std::chrono::system_clock::now());
auto seconds_since_epoch(
std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()));
// Construct time_t using 'seconds_since_epoch' rather than 'now' since it is
// implementation-defined whether the value is rounded or truncated.
std::time_t now_t(
std::chrono::system_clock::to_time_t(
std::chrono::system_clock::time_point(seconds_since_epoch)));
char temp[10];
if (!std::strftime(temp, 10, "%H:%M:%S.", std::localtime(&now_t)))
return "";
return std::string(temp) +
std::to_string((now.time_since_epoch() - seconds_since_epoch).count());
}
int main() {
std::cout << GetLocalTime() << '\n';
return 0;
}
Problem
I've tried a couple methods to print out time from the `system_clock` but I can't get anything other than whole seconds: ``` system_clock::time_point now = system_clock::now(); std::time_t now_c = system_clock::to_time_t(now); std::cout<<ctime(&now_c); std::cout<<std::put_time(std::localtime(&now_c), "%T")<<" "; ``` Does the `now()` function actually hold high precision data, or is that I just can't find the function that extracts that information for printing? Note: I am not looking to calculate a time interval. I want the current time with fractions of a second, and to print it out via `cout`. I just can't find a way to do this. And I know about `std::chrono::high_resolution_clock` but also see no way to print out its `now()`. Additionally, the `setprecision` function has no effect on the output of `put_time` or `ctime`. I've been getting answers that do not actually address this question.