# 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));
}
Run Code Online (Sandbox Code Playgroud)
当我在发布模式下运行时,会立即显示结果.但是当我在调试模式下运行时,它还没有结束.
我知道发布模式很快,但它怎么这么快?
优化编译器时可能会看到此代码:
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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
可以简单地替换为
b = 1;
Run Code Online (Sandbox Code Playgroud)
同样地,可以优化第二循环块.
此外,由于a和b不使用,可以完全去除环.
因此,您的整个程序可能会被优化为以下内容:
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));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
86 次 |
| 最近记录: |