clock()函数总是返回0 [英] clock() function always returning 0
问题描述
可能重复:
函数只返回一个零值。
Possible Duplicate:
The Cclock()
function just returns a zero
我运行下面的代码来测试clock()函数的工作。我在ubuntu 12.04上工作。
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()
返回从程序启动开始执行的刻度数 USED 。没有必要(在这个特定的)例子中得到 clock_t begin
值。
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.
尝试打印出 begin
和 end
值,看看它们是什么。
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.
不管怎样,我推荐的时间()
函数,因为您不需要 精确度。
http://www.cplusplus.com/reference/clibrary/ctime/time/
Either way, I recommend the time()
function as you don't need tick precision.
http://www.cplusplus.com/reference/clibrary/ctime/time/
这篇关于clock()函数总是返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!