Home > Software engineering >  Iomanip setprecision() Method Isn't Working as It Should Only on the First Line, Why?
Iomanip setprecision() Method Isn't Working as It Should Only on the First Line, Why?

Time:03-02

So I'm writing a program to count the execution time of a function using clock and I used iomanip to change the output to decimal with 9 zeros.

This is the code that I am using:

#include <time.h>
#include <iomanip>

using namespace std;

void linearFunction(int input)
{
    for(int i = 0; i < input; i  )
    {

    }
}

void execution_time(int input)
{
    clock_t start_time, end_time;

    start_time = clock();
    linearFunction(input);
    end_time = clock();

    double time_taken = double(end_time - start_time) / double(CLOCKS_PER_SEC);
    cout << "Time taken by function for input = " << input << " is : " << fixed
         << time_taken << setprecision(9);
    cout << " sec " << endl;
}

int main()
{
    execution_time(10000);
    execution_time(100000);
    execution_time(1000000);
    execution_time(10000000);
    execution_time(100000000);
    execution_time(1000000000);

    return 0;
}

And the output shows:

Time taken by function for input = 10000 is : 0.000000 sec
Time taken by function for input = 100000 is : 0.001000000 sec
Time taken by function for input = 1000000 is : 0.002000000 sec
Time taken by function for input = 10000000 is : 0.038000000 sec
Time taken by function for input = 100000000 is : 0.316000000 sec
Time taken by function for input = 1000000000 is : 3.288000000 sec

As you can see, the first time I call the function, it doesn't follow the setprecision(9) that I wrote. Why is this and how can I solve this? Thanks you in advance.

CodePudding user response:

Look at the following line properly:

cout << "Time taken by function for input = " << input << " is : " << fixed << time_taken << setprecision(9);

See? You are setting the precision after printing out time_taken. So for the first time, you don't see the result of setprecision(). But for the second time and onwards, as setprecision() has already been executed, you get the desired decimal places.

So to fix this issue, move setprecision() before time_taken as such:

cout << "Time taken by function for input = " << input << " is : " << fixed << setprecision(9) << time_taken;

..or you can also do something like this:

cout.precision(9);
cout << "Time taken by function for input = " << input << " is : " << fixed << time_taken;

Also, consider not using the following line in your code:

using namespace std;

..as it's considered as a bad practice. Instead use std:: every time like this:

std::cout.precision(9);
std::cout << "Time taken by function for input = " << input << " is : " << std::fixed << time_taken;

For more information on this, look up to why is "using namespace std" considered as a bad practice.

  • Related