Segmentation Fault Segmentation Fault - 10 months ago 58
C++ Question

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

This might sound like a basic question but I've searched a lot. I am trying to time-profile a function call in

& need to log the time in seconds up to
3 decimal places
. For example
2.304 seconds
.791 seconds
. I am trying to use
to do it like this:

auto start_time = std::chrono::system_clock::now();
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
only takes a few
to complete & I need the number in
. I need the number in double to use it in a different calculation.

How can I convert this weird
into a sensible number in
which yields in seconds like

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

Answer Source

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;