如何为 C 程序计时

How to time a C program

我读过这个 post here 并且我按照说明进行操作,将它们应用到一个简单的程序中,该程序将所有小于 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

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

虽然您可以在代码块之外初始化全局变量,但您不能做您正在做的事情(如果您希望代码正常工作)。一般来说,代码不应该位于函数之外。你想让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);
}

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

您必须将 beginend 移动到 main()(好吧,至少是它们的初始化)。

C程序不是自上而下执行的;它以 main() 开头。初始化文件范围变量的值必须在编译时已知,这就是你不能使用函数调用的原因。

为了获得有意义的结果,我还建议您 运行 在循环中多次测试的代码,因为时钟的分辨率通常太粗糙而无法为几条指令计时,即做一些类似的事情

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