Search code examples
c++c++11high-resolution-clock

How to convert std::chrono::high_resolution_clock::now() to milliseconds, microseconds, ...?


I got this code from How to get duration, as int milli's and float seconds from <chrono>?

#include <chrono>
#include <iostream>

int main (int argc, char *argv[])
{
  auto t0 = std::chrono::high_resolution_clock::now();
  auto t1 = std::chrono::high_resolution_clock::now();

  std::chrono::duration< double > fs = t1 - t0;
  std::chrono::milliseconds d = std::chrono::duration_cast< std::chrono::milliseconds >( fs );

  std::cout << fs.count() << "s\n";
  std::cout << d.count() << "ms\n";
}

Which works perfectly, but how I can create a time stamp with:

hour:minute:second:millisecond:microsecond:nanosecond

Using the auto t0 = std::chrono::high_resolution_clock::now() value?

I tried to print the auto t0 = std::chrono::high_resolution_clock::now(); value, to see what it had inside, however it only gave me a big error stack:

#include <chrono>
#include <iostream>

int main (int argc, char *argv[])
{
  auto t0 = std::chrono::high_resolution_clock::now();
  std::cout << t0 << "\n";
}

Error:

main2.cpp: In function 'int main(int, char**)':
main2.cpp:10:13: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long long int, std::ratio<1, 1000000000> > >')
   std::cout << t0 << "\n";
   ~~~~~~~~~~^~~~~

Solution

  • You can print a chrono::timepoint like this:

    auto t0 = std::chrono::high_resolution_clock::now();        
    auto nanosec = t0.time_since_epoch();
    
    std::cout << nanosec.count() << " nanoseconds since epoch\n";
    std::cout << nanosec.count() / (1000000000.0 * 60.0 * 60.0) << " hours since epoch\n";