Linux 为什么 C 时钟()返回 0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9871071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
why C clock() returns 0
提问by eddy ed
I've got something like this:
我有这样的事情:
clock_t start, end;
start=clock();
something_else();
end=clock();
printf("\nClock cycles are: %d - %d\n",start,end);
and I always get as an output "Clock cycles are: 0 - 0"
我总是得到一个输出“时钟周期是:0 - 0”
Any idea why this happens?
知道为什么会这样吗?
(Just to give little detail, the something_else() function performs a left-to-right exponentiation using montgomery representation, moreover I don't know for certain that the something_else() function does indeed take some not negligible time.)
(只是提供一点细节,something_else() 函数使用蒙哥马利表示执行从左到右的幂运算,而且我不确定something_else() 函数确实需要一些不可忽略的时间。)
This is on Linux. The result of uname -a is:
这是在 Linux 上。uname -a 的结果是:
Linux snowy.*****.ac.uk 2.6.32-71.el6.x86_64 #1 SMP Fri May 20 03:51:51 BST 2011 x86_64 x86_64 x86_64 GNU/Linux
Linux snowy.*****.ac.uk 2.6.32-71.el6.x86_64 #1 SMP Fri May 20 03:51:51 BST 2011 x86_64 x86_64 x86_64 GNU/Linux
采纳答案by ouah
clockfunction does not measure CPU clock cycles.
clock函数不测量 CPU 时钟周期。
C says clock"returns the implementation's best approximationto the processor
time used by the program since the beginning of an implementation-defined era related
only to the program invocation."
C 表示clock“返回实现对程序使用的处理器时间的最佳近似,自一个实现定义的时代开始,仅与程序调用相关。”
If between two successive clockcalls you program takes less time than one unity of the clockfunction, you could get 0.
如果在两次连续clock调用之间,您编程的时间少于clock函数的一个统一体,您可以获得0.
POSIX clockdefines the unity with CLOCKS_PER_SECas 1000000 (unity is then 1 microsecond).
POSIXclock将统一定义CLOCKS_PER_SEC为 1000000(统一为 1 微秒)。
http://pubs.opengroup.org/onlinepubs/009604499/functions/clock.html
http://pubs.opengroup.org/onlinepubs/009604499/functions/clock.html
To measure clock cycles in x86/x64 you can use inline assembly to retreive the clock count of the CPU Time Stamp Counter register rdtsc.
要测量 x86/x64 中的时钟周期,您可以使用内联汇编来检索 CPU 时间戳计数器寄存器的时钟计数rdtsc。
回答by Enrique Marcos
Well, do you want the time something_else()takes? Try this:
那么,你想要时间something_else()吗?尝试这个:
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
int main(void) {
struct timeval start, end;
long mtime, secs, usecs;
gettimeofday(&start, NULL);
something_else();
gettimeofday(&end, NULL);
secs = end.tv_sec - start.tv_sec;
usecs = end.tv_usec - start.tv_usec;
mtime = ((secs) * 1000 + usecs/1000.0) + 0.5;
printf("Elapsed time: %ld millisecs\n", mtime);
return 0;
}
回答by Pavan Manjunath
Check the value of CLOCKS_PER_SECin time.h/clock.h. On my system, for example, ( Dev Cpp on Windows 7 ) its a mere 1000. So as far as my program is concerned, there are 1000 ticks per second. Your something_elsewould be executed in a matter of microseconds. And hence clock()returns zero both before and after the function call.
检查CLOCKS_PER_SECin的值time.h/clock.h。例如,在我的系统上,(Windows 7 上的 Dev Cpp)它只是一个1000. 所以就我的程序而言,每秒有 1000 个滴答声。您something_else将在几微秒内执行。因此clock()在函数调用之前和之后都返回零。
On my system, when I replace your something_elsewith a time consuming routine like this
在我的系统上,当我something_else用这样一个耗时的例程替换你的时候
for (unsigned i=0xFFFFFFFF;i--;);
start=clock();
for (unsigned i=0xFFFFFFFF;i--;);
end=clock();
I get
我得到
Clock cycles are: 10236 - 20593
时钟周期为:10236 - 20593
On one of linux boxes, I find the following in bits/time.h
在其中一个 linux 机器上,我发现以下内容 bits/time.h
/* ISO/IEC 9899:1990 7.12.1: <time.h>
The macro `CLOCKS_PER_SEC' is the number per second of the value
returned by the `clock' function. */
/* CAE XSH, Issue 4, Version 2: <time.h>
The value of CLOCKS_PER_SEC is required to be 1 million on all
XSI-conformant systems. */
# define CLOCKS_PER_SEC 1000000l
So do consider this before analyzing the return value of clock()
所以在分析返回值之前一定要考虑这一点 clock()
回答by Guido
The right way of using clock() to measure time would be:
使用 clock() 测量时间的正确方法是:
printf("\nTime elapsed: %.2f\n",1.0*(end-start)/CLOCKS_PER_SEC);
This is because clock_t isn't guaranteed to be an int, or any other type for that matter.
这是因为不能保证 clock_t 是 int 或任何其他类型。
回答by Jinghao Shi
I guess the reason is that your something_else()consumes so little time that exceed the precision of clock(). I tried calling clock()twice consequently and both startand endis zero, but result is reasonable when I do some time-consuming stuff between.
我想原因是你something_else()消耗的时间太少,超过了clock(). 我试着打电话clock()因而两次,都start和end是零,但结果是合理的,当我做之间的一些费时的东西。
Here is my test code snippet:
这是我的测试代码片段:
int main(void) {
clock_t start, end;
start = clock();
int c;
for (int i = 0; i < 100; i++) {
for (int j = 0; j < (1<<30); j++) {
c++;
}
}
end = clock();
printf("start = %d, end = %d\n", start, end);
return 0;
}
And the result on my computer is:
我电脑上的结果是:
start = 0, end = 27700000
Also, two tips:
还有两个小技巧:
- When testing, do not use any compiler optimization. You may think your
something_else()is time-consuming but the compiler may just ignore those operations (especially loops) since it think them as meaningless. - Use
sizeof(clock_t)on your platform to see the size ofclock_t.
- 测试时,不要使用任何编译器优化。您可能认为您的操作
something_else()很耗时,但编译器可能会忽略这些操作(尤其是循环),因为它认为它们毫无意义。 sizeof(clock_t)在您的平台上使用以查看clock_t.
回答by user3782374
I have used the little program below to investigate wall clock time and CPU time.
我使用下面的小程序来研究挂钟时间和 CPU 时间。
On my test sytem this prints
在我的测试系统上打印
CLOCKS_PER_SEC 1000000
CLOCKS_PER_SEC 1000000
CPU time usage resolution looks to be 0.010000 seconds
CPU time usage resolution 看起来是 0.010000 seconds
gettimeofday changed by 9634 uSwhen CPU time changed by 0.010000
gettimeofday 更改为9634 uSCPU 时间更改时间0.010000
gettimeofday resolution looks to be 1 us
gettimeofday 分辨率看起来是 1 us
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <ctime>
int main(int argc, char** argv) {
struct timeval now; // wall clock times
struct timeval later;
clock_t tNow = clock(); // clock measures CPU time of this Linux thread
gettimeofday(&now, NULL); // wall clock time when CPU time first read
clock_t tLater = tNow;
while (tNow == tLater)
tLater = clock(); // consume CPU time
gettimeofday(&later, NULL); // wall clock time when CPU time has ticked
printf("CLOCKS_PER_SEC %ld\n",CLOCKS_PER_SEC);
double cpuRes = (double)(tLater - tNow)/CLOCKS_PER_SEC;
printf("CPU time usage resolution looks to be %f seconds\n", cpuRes);
unsigned long long nowUs = ((unsigned long long)now.tv_sec) * 1000000ULL;
nowUs += (unsigned long long)now.tv_usec;
unsigned long long laterUs = ((unsigned long long)later.tv_sec) * 1000000ULL;
laterUs += (unsigned long long)later.tv_usec;
printf("gettimeofday changed by %d uS when CPU time changed by %f seconds\n", (int)(laterUs - nowUs), cpuRes);
// now measure resolution of gettimeofday
gettimeofday(&now, NULL);
later = now;
while ((now.tv_sec == later.tv_sec) && (now.tv_usec == later.tv_usec))
gettimeofday(&later, NULL);
nowUs = ((unsigned long long)now.tv_sec) * 1000000ULL;
nowUs += (unsigned long long)now.tv_usec;
laterUs = ((unsigned long long)later.tv_sec) * 1000000ULL;
laterUs += (unsigned long long)later.tv_usec;
printf("gettimeofday resolution looks to be %d us\n", (int)(laterUs - nowUs));
}
回答by Michael G. Workman
I encountered this same issue while trying to time the difference between a generic class and a non-generic class both using a vector, on Red Hat Linux with C++ and g++ compiler. It appears if your program runs slower than a single clock, the clock() reading will always be zero (0).
我在尝试使用向量计算泛型类和非泛型类之间的差异时遇到了同样的问题,在 Red Hat Linux 上使用 C++ 和 g++ 编译器。看起来如果您的程序运行速度比单个时钟慢,则 clock() 读数将始终为零 (0)。
This code will always return 0
此代码将始终返回 0
#include <iostream>
#include <ctime>
using namespace std;
int main() {
cout << clock() << endl;
return 0;
}
When I added a for loop with an index up to ten million, to slow the program down, then I got a number 20000 as the result from clock()
当我添加一个索引高达 1000 万的 for 循环以减慢程序速度时,我从 clock() 得到了一个数字 20000
#include <iostream>
#include <ctime>
using namespace std;
int main() {
for (int i = 0; i < 10000000; i++) {}
cout << clock() << endl;
return 0;
}
Certainly depending on the stats of your box, the results will vary, I am running this code with multi-processor Xeon CPU's and also a huge amount of RAM.
当然,根据您的机器的统计数据,结果会有所不同,我正在使用多处理器至强 CPU 和大量 RAM 运行此代码。

