Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ chrono: Get seconds with a precision of 3 decimal places

Tags:

c++

c++-chrono

This might sound like a basic question but I've searched a lot. I am trying to time-profile a function call in C++ & need to log the time in seconds up to 3 decimal places. For example 2.304 seconds or .791 seconds. I am trying to use std::chrono to do it like this:

auto start_time = std::chrono::system_clock::now();
DoSomeOperation();
std::chrono::duration<double> elapsed_time = std::chrono::system_clock::now() - start_time;
double execution_time = elapsed_time.count();

std::cout << "execution_time = " << execution_time << std::endl;

Following is the output I am getting:

execution_time = 1.9e-05
execution_time = 2.1e-05
execution_time = 1.8e-05
execution_time = 1.7e-05

I am sure that DoSomeOperation only takes a few milliseconds to complete & I need the number in seconds. I need the number in double to use it in a different calculation.

How can I convert this weird 1.9e-05 into a sensible number in double which yields in seconds like .304 or .067 ?

Trying the code from here, I've the same problem.

like image 781
TheWaterProgrammer Avatar asked Sep 11 '25 20:09

TheWaterProgrammer


1 Answers

To change the output format, try std::fixed and std::setprecision

double execution_time = 0.01234;
std::cout << "execution_time = "
          << std::fixed << std::setprecision(3)
          << execution_time << std::endl;

If you have several places where you need to output the execution time, it can be converted to a string and then re-used:

double execution_time = 0.01234;
std::stringstream stream;
stream << std::fixed << std::setprecision(3) << execution_time;
std::string execution_time_as_string = stream.str();

std::cout << "execution_time = " << execution_time_as_string << std::endl;
like image 141
AlexD Avatar answered Sep 13 '25 10:09

AlexD