问题
Possible Duplicate:
The C clock() 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?
回答1:
clock()
returns the number of ticks USED SINCE THE PROGRAM STARTED executing. There is no need (in this specific) example to get the clock_t begin
value.
Try printing out both the begin
and end
values 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/
回答2:
I think you should be using the time() function. Here is how it works: http://asust.in/007D You just call it and it returns the number of seconds since Unix epoch (January 1, 1970).
The clock() function returns the number of clock ticks since the program started. Here: http://asust.in/007E
来源:https://stackoverflow.com/questions/11976342/clock-function-always-returning-0