Croset
Croset

Reputation: 37

How to show execution time in the command box output?

Okay, completely revamped my question now I have figured out the time issue. So now this is what my code looks like;

int main()

{
    int start_s = clock();
    int i, n = 10;
    int sum = 0;

    for (i = 0; i < n; ++i)
    {
        cout << "Sum: " << sum << "\n";
        ++sum;
        int stop_s = clock();
        cout << "time: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000 << endl;
        system("pause");
    }
}

but now my issue is that the execution time is showing in weirdnumbers, for example the first time I run it I get say time: 1, then run again it goes up to something strange like time: 4000, etc.. I want time in milliseconds if possible, or something like 0.0043 for time.

Thanks for the help!

Upvotes: 1

Views: 68

Answers (1)

Ashish K
Ashish K

Reputation: 935

You have to cast (stop_s - start_s) in double. Look at the code below.

t = (stop_s - start_s);
double time_taken = (((double)t)/CLOCKS_PER_SEC) * 1000; //time in milliseconds


int main()

{
    int start_s = clock();
    int i, n = 10;
    int sum = 0;

    for (i = 0; i < n; ++i)
    {
        cout << "Sum: " << sum << "\n";
        ++sum;
        int stop_s = clock();
        double t = double (stop_s - start_s);
        cout << "time: " << (t / double(CLOCKS_PER_SEC)) * 1000 << endl;
        system("pause");
    }
}

This should work, however I cannot test it right now.

Upvotes: 1

Related Questions