c - 如何为 C 程序计时

标签 c time compiler-errors initialization

我读过这篇文章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

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

最佳答案

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

您必须将 beginend 移至 main() 中(嗯,至少是它们的初始化)。

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

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

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

关于c - 如何为 C 程序计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34120378/

相关文章:

c - C 中表达式的等价性

c - 根据用户输入决定动态分配多少内存

java - Java 计时器领域的现状如何?

r - `as.POSIXct` 与 Excel 的数据差异

angular - 由于 'Can' t构造了属性..的查询,因此导致 Angular AOT编译失败。

makefile - 在Windows上编译OpenSSL MinGw-make [1] : *** [Makefile:2800: crypto/dso/dso_win32.o] Error 1

c# - C# 中的 C 方法 Fread() 等效项

c - 为什么按回车不返回 '\n' 到 getch()?

java - 双嵌套for循环之间的复杂性差异? ( java )

c# - 为什么这种编译方式有所不同?