1

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!

Croset
  • 37
  • 6
  • Possible duplicate of [How to Calculate Execution Time of a Code Snippet in C++](http://stackoverflow.com/questions/1861294/how-to-calculate-execution-time-of-a-code-snippet-in-c) – Jonny Henly Mar 21 '17 at 04:34

1 Answers1

1

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.

Ashish K
  • 905
  • 10
  • 27
  • Thank you for this I really appreciate it! I'm not sure how to implement that in my code though? does t = (stop_s - start_s); replace int stop_s = clock() ? – Croset Mar 21 '17 at 19:52
  • thank you! Im getting a couple errors on t = (stop_s - start_s); saying identifier undefined, trying to work through it as im still new to this! Thanks :) – Croset Mar 21 '17 at 20:32
  • go ahead! let me know if you are unable to proceed. I will surely help – Ashish K Mar 21 '17 at 20:33
  • unexpected identifier is usually because when you do not include the header. Have you included time.h ?? – Ashish K Mar 21 '17 at 20:36
  • Thanks for your help! I have done that yes, the "t" says this declaration has no storage type, and im getting an error for "stop_s" and "start_s" saying identifier is undefined? – Croset Mar 21 '17 at 20:42