如何计时一个C程序
如何计时一个C程序
我阅读了这篇帖子here并按照说明进行操作,将其应用于一个简单的程序,该程序对3和5的倍数之下的所有数字求和。\n
#include#include clock_t begin, end; double time_spent; begin = clock(); int sumDivisibleBy (div, limit) { int h = (limit - 1)/div; return div*h*(h+1)/2; } int main(void) { int l = 1000; int s = sumDivisibleBy(3,l) + sumDivisibleBy(5,l) - sumDivisibleBy(15,l); printf("%d \n", s); } end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC printf("%f \n", time_spent)
\n现在,当我在终端中输入\"make 1\"(文件名为1.c)时,我得到以下结果:\n
cc 1.c -o 1 1.c:9:1: warning: data definition has no type or storage class [enabled by default] begin = clock(); ^ 1.c:9:1: error: conflicting types for ‘begin’ 1.c:6:9: note: previous declaration of ‘begin’ was here clock_t begin, end; ^ 1.c:9:1: error: initializer element is not constant begin = clock(); ^ 1.c:20:1: warning: data definition has no type or storage class [enabled by default] end = clock(); ^ 1.c:20:1: error: conflicting types for ‘end’ 1.c:6:16: note: previous declaration of ‘end’ was here clock_t begin, end; ^ 1.c:20:1: error: initializer element is not constant end = clock(); ^ 1.c:21:1: warning: data definition has no type or storage class [enabled by default] time_spent = (double)(end - begin) / CLOCKS_PER_SEC ^ 1.c:21:1: error: conflicting types for ‘time_spent’ 1.c:7:8: note: previous declaration of ‘time_spent’ was here double time_spent; ^ 1.c:21:1: error: initializer element is not constant time_spent = (double)(end - begin) / CLOCKS_PER_SEC ^ 1.c:21:1: error: expected ‘,’ or ‘;’ at end of input make: *** [1] Error 1
\n为什么会这样?有人可以帮忙吗?
问题出现的原因是全局变量的初始化不能放在代码块外部,如果想要代码正常工作,就不能将代码放在函数外面。通常情况下,代码不应该放在函数外部。你希望end = clock()
在程序结尾时执行!为了做到这一点,它需要放在main()
函数的结尾。
解决方法是将代码移入main()
函数中,使其如下所示:
int main(void) { begin = clock(); ... //代码放在这里 end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("time spent %f \n", time_spent); }
如何计时C程序
在C语言中,你不能使用函数调用来初始化文件范围的变量(即在main函数之外的变量)。你必须将begin和end移动到main函数中(至少它们的初始化部分)。C程序不是从上到下执行的;它从main函数开始执行。初始化的文件范围变量的值必须在编译时就已知,这就是为什么不能使用函数调用的原因。
为了得到有意义的结果,我建议你在一个循环中多次运行要测试的代码,因为时钟的分辨率通常太粗糙,无法测量几个指令的时间。你可以这样做:
begin = ... for (j = 0; j < 10000; ++j) { code_to_test(); } end = ...
这是个好消息。现在,在Stack Overflow上的下一步是通过点击左边的勾选标记来接受你认为最有帮助的答案。这将为你赚取两个声望点。
是的,我本想立即这样做,但他让我等待4分钟。
在这种情况下,它们是等效的。我更喜欢++j而不是j++,因为在我的思维中,我读代码时是“增加j”,而不是“j,递增它”。