Possible Duplicate:
The Cclock()function just returns a zero
I ran the following code to test the working of clock() function. I work on ubuntu 12.04.
#include <stdio.h>
#include <time.h>
#include <iostream>
using namespace std;
double diffclock(clock_t clock1,clock_t clock2)
{
double diffticks=clock1-clock2;
double diffms=(diffticks*10)/CLOCKS_PER_SEC;
return diffms;
}
int main()
{
string name;
int i;
clock_t begin=clock();
cout << "Hi what is your name? ";
getline(cin, name);
clock_t end=clock();
cout << "Time elapsed: " << double(diffclock(end,begin)) << " ms"<< endl;
return 0;
}
But no matter how much time i take to write my name, the time elapsed is always shown as 0ms.
Can you tell me what is the problem?
clock()returns the number of ticks USED SINCE THE PROGRAM STARTED executing. There is no need (in this specific) example to get theclock_t beginvalue.Try printing out both the
beginandendvalues and see what they are. They’re likely both 0 or close to 0 as waiting for user input doesn’t use CPU time.Either way, I recommend the
time()function as you don’t need tick precision.http://www.cplusplus.com/reference/clibrary/ctime/time/