Will_of_fire
Will_of_fire

Reputation: 1189

Measuring the running time of a program using clock() function

#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.

Upvotes: 0

Views: 113

Answers (1)

xcodedeveloper
xcodedeveloper

Reputation: 276

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?

Upvotes: 1

Related Questions