42
4

4 回答 4

45

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() << '\n';
}

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() << '\n';

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() << '\n';
}

Output:

147901305796958ns
于 2011-10-25T13:22:10.580 回答
24

A quick google search found this page: http://en.cppreference.com/w/cpp/chrono/duration, where you can find an example of printing a duration.

Edit: it got moved to http://en.cppreference.com/w/cpp/chrono/duration/duration_cast

于 2011-10-25T12:33:28.847 回答
11

If you want timing in resolution of milliseconds this is how you can do it:

auto t1 = std::chrono::high_resolution_clock::now();
//process to be timed
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "process took: "
    << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count()
    << " milliseconds\n";

Don't forget to add among the included headers:

#include <chrono> //timing
于 2015-05-20T15:27:09.147 回答
7

Not sure what you expect from this cast, maybe you wanted t.time_since_epoch().count()?

于 2011-10-25T12:34:55.480 回答