0
#include <iostream>
#include <ctime>

using namespace std;

int main()
{
    clock_t t;
    t = clock();
    for(int i=0;i<1000000;i++)
        ;
    t=clock()-t;
    cout<<(float)t/CLOCKS_PER_SEC<<endl;
    return 0;
}

I wrote a sample c++ program to measure the running time. Every time I run this code I get a different output. How is this happening? Shouldn't the time required by this program be same every time I run it.

Will_of_fire
  • 1,089
  • 4
  • 12
  • 24
  • 4
    ***Shouldn't the time required by this program be same every time I run it*** Not necessarily, remember your OS can schedule some other task ahead of your program.. Your CPU can change its frequency based on load or even temperature. – drescherjm Dec 14 '16 at 02:43
  • @drescherjm Thanks!!! That makes sense. – Will_of_fire Dec 14 '16 at 02:48

1 Answers1

1

I think that your running time you had is true. In the multitasking operating system, we have multi thread, so when your program running, maybe other program request CPU and your program to be comming delay for it. You should read: Easily measure elapsed time
If you are curious about the game timer program. You can use the game loop. follows this: How to make timer for a game loop?

Community
  • 1
  • 1
xcodedeveloper
  • 266
  • 2
  • 8