繁体   English   中英

如何计时一个C程序

[英]How to time a C program

我在这里阅读了这篇文章并按照说明进行了操作,将它们应用于一个简单的程序,该程序将1000以下的所有数字相加,并被3和5整除。

#include <stdio.h>
#include <time.h>

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)

现在,当我在终端上输入“ make 1”(文件称为1.c)时,这就是我得到的:

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

为什么? 有人可以帮忙吗?

您不能使用函数调用来初始化文件范围变量(那些在main之外的变量)。

您必须将beginend移到main() (至少要初始化它们)。

AC程序没有从上到下执行; 它以main()开头。 必须在编译时知道已初始化文件作用域变量的值,这就是您不能使用函数调用的原因。

为了获得有意义的结果,我还建议您循环运行要测试的代码多次,因为时钟的分辨率通常太粗糙,无法计时一些指令,即执行类似的操作

 begin = ...
 for (j = 0; j < 10000; ++j) {
     code_to_test();
 }
 end = ...

虽然可以在代码块外部初始化全局变量,但是您不能做自己正在做的事情(如果要使代码工作)。 通常,代码不应位于函数之外。 您希望end = clock()最后执行! 为此,它必须位于main()函数的末尾。

将代码移到main()中,它显示为:

int main(void) {
    begin = clock();

    ... //your code here

    end = clock();
    time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
    printf("time spent %f \n", time_spent);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM