gpt4 book ai didi

c - 为什么在release模式和debug模式下执行结果会出现很大差异?

转载 作者:太空宇宙 更新时间:2023-11-04 05:22:50 24 4
gpt4 key购买 nike

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

int main() {
clock_t start;
long a = 0;
long b = 0;

start = clock();
for (int i = 0; i < INT_MAX; i++) {
for (int j = 0; j < INT_MAX; j++) {
for (int k = 0; k < INT_MAX; k++) {
for (int q = 0; q < INT_MAX; q++) {
b = 1;
}
}
}
}
printf("%.5f\n", ((float)(clock() - start) / CLOCKS_PER_SEC));

start = clock();
for (int i = 0; i < INT_MAX; i++) {
for (int j = 0; j < INT_MAX; j++) {
for (int k = 0; k < INT_MAX; k++) {
a = 0;
for (int q = 0; q < INT_MAX; q++) {
a += 1;
}
}
}
}
printf("%.5f\n",((float)(clock()-start)/CLOCKS_PER_SEC));
}

当我在 Release模式下运行时,这会立即显示结果。但是当我在 Debug 模式下运行时,它还没有结束。

我知道release模式很快,但是怎么会这么快呢?

最佳答案

优化编译器的时候可能会看到这段代码:

for (int i = 0; i < INT_MAX; i++) {
for (int j = 0; j < INT_MAX; j++) {
for (int k = 0; k < INT_MAX; k++) {
for (int q = 0; q < INT_MAX; q++) {
b = 1;
}
}
}
}

可以简单地替换为

b = 1;

同样可以优化第二个循环 block 。

此外,由于未使用 ab,因此可以完全删除循环。

所以你的整个程序可能会被优化成代表:

int main() {
clock_t start;
start = clock();
printf("%.5f\n", ((float)(clock() - start) / CLOCKS_PER_SEC));
start = clock();
printf("%.5f\n",((float)(clock()-start)/CLOCKS_PER_SEC));
}

关于c - 为什么在release模式和debug模式下执行结果会出现很大差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53096137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com