Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

c++ - std::chrono and cout

I have a stupid problem. I try to switch to the c++11 headers and one of those is chrono. But my problem is that I cant cout the result of time operations. For example:

auto t=std::chrono::high_resolution_clock::now();
cout<<t.time_since_epoch();

gives:

initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char, _Traits = std::char_traits<char>, _Tp = std::chrono::duration<long int, std::ratio<1l, 1000000l> >]’ ... /usr/include/c++/4.6/ostream

cout<<(uint64_t)t.time_since_epoch();

gives invalid cast

question from:https://stackoverflow.com/questions/7889136/stdchrono-and-cout

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As others have noted, you can call the count() member function to get the internal count.

I wanted to add that I am attempting to add a new header: <chrono_io> to this library. It is documented here. The main advantage of <chrono_io> over just using count() is that the compile-time units are printed out for you. This information is of course obtainable manually, but it is much easier to just have the library to it for you.

For me, your example:

#include <iostream>
#include <chrono_io>

int main()
{
    auto t = std::chrono::high_resolution_clock::now();
    std::cout << t.time_since_epoch() << '
';
}

Outputs:

147901305796958 nanoseconds

The source code to do this is open source and available at the link above. It consists of two headers: <ratio_io> and <chrono_io>, and 1 source: chrono_io.cpp.

This code should be considered experimental. It is not standard, and almost certainly will not be standardized as is. Indeed preliminary comments from the LWG indicate that they would prefer the default output to be what this software calls the "short form". This alternative output can be obtained with:

std::cout << std::chrono::duration_fmt(std::chrono::symbol)
          << t.time_since_epoch() << '
';

And outputs:

147901305796958 ns

Update

It only took a decade, but C++20 now does:

#include <chrono>
#include <iostream>

int main()
{
    auto t = std::chrono::high_resolution_clock::now();
    std::cout << t.time_since_epoch() << '
';
}

Output:

147901305796958ns

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...