How do you print a C++11 time_point?

2020-02-07 17:37发布

I've created a time point, but I have been struggling to print it to the terminal.

#include <iostream>
#include <chrono>

int main(){

    //set time_point to current time
    std::chrono::time_point<std::chrono::system_clock,std::chrono::nanoseconds> time_point;
    time_point = std::chrono::system_clock::now();

    //print the time
    //...

    return 0;
}

The only documentation I can find that prints a time_point is found here: http://en.cppreference.com/w/cpp/chrono/time_point

however, I'm not even able to create a time_t based on my time_point(like the example).

std::time_t now_c = std::chrono::system_clock::to_time_t(time_point); //does not compile

Error:

/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono: In instantiation of ‘constexpr std::chrono::time_point<_Clock, _Dur>::time_point(const std::chrono::time_point<_Clock, _Dur2>&) [with _Dur2 = std::chrono::duration<long int, std::ratio<1l, 1000000000l> >; _Clock = std::chrono::system_clock; _Dur = std::chrono::duration<long int, std::ratio<1l, 1000000l> >]’:
time.cpp:13:69:   required from here
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:540:32: error: no matching function for call to ‘std::chrono::duration<long int, std::ratio<1l, 1000000l> >::duration(std::chrono::time_point<std::chrono::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000000l> > >::duration)’
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:540:32: note: candidates are:
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:247:14: note: template<class _Rep2, class _Period2, class> constexpr std::chrono::duration::duration(const std::chrono::duration<_Rep2, _Period2>&)
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:247:14: note:   template argument deduction/substitution failed:
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:243:46: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:240:23: note: template<class _Rep2, class> constexpr std::chrono::duration::duration(const _Rep2&)
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:240:23: note:   template argument deduction/substitution failed:
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:236:27: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:234:12: note: constexpr std::chrono::duration<_Rep, _Period>::duration(const std::chrono::duration<_Rep, _Period>&) [with _Rep = long int; _Period = std::ratio<1l, 1000000l>]
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:234:12: note:   no known conversion for argument 1 from ‘std::chrono::time_point<std::chrono::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000000l> > >::duration {aka std::chrono::duration<long int, std::ratio<1l, 1000000000l> >}’ to ‘const std::chrono::duration<long int, std::ratio<1l, 1000000l> >&’
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:232:12: note: constexpr std::chrono::duration<_Rep, _Period>::duration() [with _Rep = long int; _Period = std::ratio<1l, 1000000l>]
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/chrono:232:12: note:   candidate expects 0 arguments, 1 provided

6条回答
▲ chillily
2楼-- · 2020-02-07 17:47

For anyone working with time_point<steady_clock> (not time_point<system_clock>):

#include <chrono>
#include <iostream>

template<std::intmax_t resolution>
std::ostream &operator<<(
    std::ostream &stream,
    const std::chrono::duration<
        std::intmax_t,
        std::ratio<std::intmax_t(1), resolution>
    > &duration)
{
    const std::intmax_t ticks = duration.count();
    stream << (ticks / resolution) << '.';
    std::intmax_t div = resolution;
    std::intmax_t frac = ticks;
    for (;;) {
        frac %= div;
        if (frac == 0) break;
        div /= 10;
        stream << frac / div;
    }
    return stream;
}

template<typename Clock, typename Duration>
std::ostream &operator<<(
    std::ostream &stream,
    const std::chrono::time_point<Clock, Duration> &timepoint)
{
    typename Duration::duration ago = timepoint.time_since_epoch();
    return stream << ago;
}

int main(){
    // print time_point
    std::chrono::time_point<std::chrono::steady_clock> now =
        std::chrono::steady_clock::now();
    std::cout << now << "\n";

    // print duration (such as the difference between 2 time_points)
    std::chrono::steady_clock::duration age = now - now;
    std::cout << age << "\n";
}

The decimal number formatter is not the most efficient, but needs no beforehand knowledge of the number of decimals, which is not known if you want resolution to be templated, unless you can come up with a constant expression for ceil(log10(resolution)).

查看更多
家丑人穷心不美
3楼-- · 2020-02-07 17:52

The nanoseconds seems to be part of the problem, looking at the documentation a bit I was able to get this to work:

#include <iostream>
#include <chrono>
#include <ctime>


int main(){

    //set time_point to current time
    std::chrono::time_point<std::chrono::system_clock> time_point;
    time_point = std::chrono::system_clock::now();

    std::time_t ttp = std::chrono::system_clock::to_time_t(time_point);
    std::cout << "time: " << std::ctime(&ttp);

    return 0;
}

Although it looks like std::chrono::microseconds works ok:

std::chrono::time_point<std::chrono::system_clock,std::chrono::microseconds> time_point;
查看更多
爷、活的狠高调
4楼-- · 2020-02-07 17:54

Updated answer for an old question:

For a std::chrono::time_point<std::chrono::system_clock, some-duration> there is now a 3rd party libraries that give you much better control. For time_points based on other clocks, there is still no better solution than to just get the internal representation and print it out.

But for system_clock, using this library, this is as easy as:

#include "date.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    std::cout << system_clock::now() << " UTC\n";
}

which just output for me:

2016-07-19 03:21:01.910626 UTC

which is the current UTC date and time to microsecond precision. If on your platform system_clock::time_point has nanosecond precision, it will print out nanosecond precision for you.

查看更多
Emotional °昔
5楼-- · 2020-02-07 17:56

(In this post I will omit std::chrono:: qualifications for clarity. I trust you know where they go.)

The reason your code example fails to compile is that there is a mismatch between the return type of system_clock::now() and the type of variable you are trying to assign this to (time_point<system_clock, nanoseconds>).

The documented return value of system_clock::now() is system_clock::time_point, which is a typedef for time_point<system_clock, system_clock::duration>. system_clock::duration is implementation-defined, with microseconds and nanoseconds being commonly used. It seems that your implementation uses microseconds, so the return type of system_clock::now() is time_point<system_clock, microseconds>.

time_points with different durations are not implicitly convertible to one another, so you get a compiler error.

You can explicitly convert time points with different durations using time_point_cast, so the following would compile on your system:

time_point<system_clock, nanoseconds> time_point;
time_point = time_point_cast<nanoseconds>(system_clock::now());

Notice the explicit template parameter to time_point_cast is the target duration type, not the target time_point type. The clock types must match in a time_point_cast, so specifying the entire time_point type (which is templated on both the clock type and the duration type) would be redundant.

Of course in your case, since you are just looking to print the time point, there is no need for it to be at any specific resolution, so you can just declare time_point to be the same type as what system_clock::now() returns to begin with. A simple way to do that is to use the system_clock::time_point typedef:

system_clock::time_point time_point;
time_point = system_clock::now();  // no time_point_cast needed

Since this is C++11, you can also just use auto:

auto time_point = system_clock::now(); 

Having solved this compiler error, the conversion to time_t works just fine:

std::time_t now_c = std::chrono::system_clock::to_time_t(time_point);

and you can now use standard methods for displaying time_t values, like std::ctime or std::strftime. (As Cassio Neri points out in a comment to your question, the more C++-y std::put_time function is not yet supported by GCC).

查看更多
祖国的老花朵
6楼-- · 2020-02-07 18:06

The ctime() does not work for Visual C++. I use MS Visual Studio 2013. I changed the above code to use ctime_s(...), as prompted by MSVC compiler. It worked.

//set time_point to current time
std::chrono::time_point<std::chrono::system_clock> time_point;
time_point = std::chrono::system_clock::now();

std::time_t ttp = std::chrono::system_clock::to_time_t(time_point);
char chr[50];
errno_t e = ctime_s(chr, 50, &ttp);
if (e) std::cout << "Error." << std::endl;
else std::cout << chr << std::endl;
查看更多
Emotional °昔
7楼-- · 2020-02-07 18:08

This snippet might help you:

#include <iomanip>
#include <iostream>
#include <chrono>
#include <ctime>

template<typename Clock, typename Duration>
std::ostream &operator<<(std::ostream &stream,
  const std::chrono::time_point<Clock, Duration> &time_point) {
  const time_t time = Clock::to_time_t(time_point);
#if __GNUC__ > 4 || \
    ((__GNUC__ == 4) && __GNUC_MINOR__ > 8 && __GNUC_REVISION__ > 1)
  // Maybe the put_time will be implemented later?
  struct tm tm;
  localtime_r(&time, &tm);
  return stream << std::put_time(&tm, "%c"); // Print standard date&time
#else
  char buffer[26];
  ctime_r(&time, buffer);
  buffer[24] = '\0';  // Removes the newline that is added
  return stream << buffer;
#endif
}

int main() {
  std::cout << std::chrono::system_clock::now() << std::endl;
  // Wed May 22 14:17:03 2013
}
查看更多
登录 后发表回答