我尝试了以下3个for
循环:
#define loop 1000000000
NSDate *start;
NSDate *end;
// 1: empty for loop
start = [NSDate date];
for (NSInteger i = 0; i < loop; i++) {
}
end = [NSDate date];
NSLog(@"time interval: %f", [end timeIntervalSince1970] - [start timeIntervalSince1970]);
// 2: do-while for loop
start = [NSDate date];
for (NSInteger i = 0; i < loop; i++) {
do {
} while (0);
}
end = [NSDate date];
NSLog(@"time interval: %f", [end timeIntervalSince1970] - [start timeIntervalSince1970]);
// 3: @try-@finally for loop
start = [NSDate date];
for (NSInteger i = 0; i < loop; i++) {
@try {
}
@finally {
}
}
end = [NSDate date];
NSLog(@"time interval: %f", [end timeIntervalSince1970] - [start timeIntervalSince1970]);
我在'07 Macbook Pro上测试了这三个for
循环大约10亿个。我记录了时间戳来计算执行持续时间。结果如下:
1: empty for loop => 2.947088 sec
2: do-while for loop => 2.581905 sec
3: @try-@finally for loop => 4.216685 sec
什么? do-while for
循环比空for
循环快!
为什么?
已更新
我在for
循环中添加了一些额外的代码(j ++):
NSInteger j;
#define loop 1000000000
// 1: empty for loop
j = 0
for (NSInteger i = 0; i < loop; i++) {
j++;
}
// 2: do-while for loop
j = 0;
for (NSInteger i = 0; i < loop; i++) {
do {
j++;
} while (0);
}
// 3: @try-@finally for loop
j = 0;
for (NSInteger i = 0; i < loop; i++) {
@try {
j++;
}
@finally {
}
}
输出:
1: empty for loop => 2.590103 sec
2: do-while for loop => 2.138528 sec
3: @try-@finally for loop => 3.983589 sec
这3个比以前的代码快得多,并且do-while for
循环仍然是最快的。怪异!
答案 0 :(得分:10)
不是。输出很大程度上取决于所使用的特定编译器以及有效的优化设置。任何值得盐的编译器都会优化掉两个循环。当我编译以下示例代码时,Clang和GCC都会在任何非零优化级别(即-O1
及以上)完全删除循环:
#include <stdio.h>
#include <stdint.h>
#include <sys/time.h>
#define loop 1000000000
int main(void)
{
struct timeval t1, t2, t3;
gettimeofday(&t1, NULL);
for (long i = 0; i < loop; i++) {
}
gettimeofday(&t2, NULL);
for (long i = 0; i < loop; i++) {
do {
} while (0);
}
gettimeofday(&t3, NULL);
int64_t d1 = (t2.tv_sec - t1.tv_sec) * 1000000ll + (t2.tv_usec - t1.tv_usec);
int64_t d2 = (t3.tv_sec - t2.tv_sec) * 1000000ll + (t3.tv_usec - t2.tv_usec);
printf("Empty for loop: %lld.%06d\n", d1 / 1000000, (int)(d1 % 1000000));
printf("do-while for loop: %lld.%06d\n", d2 / 1000000, (int)(d2 % 1000000));
return 0;
}
在优化级别0(-O0
,未优化的代码)处,Clang和GCC都生成代码,其中两个循环以相同的速度运行(在实验性错误内),或者do-while循环运行稍慢额外的未经优化的代码。我在64位Mac上的结果,使用Clang 4.1和GCC 4.2.1:
Clang, 32-bit, -O0:
Empty for loop: 2.632714
do-while for loop: 2.633194
Clang, 64-bit, -O0:
Empty for loop: 2.632078
do-while for loop: 2.632046
Clang, 32-bit, -O1:
Empty for loop: 0.000000
do-while for loop: 0.000000
Clang, 64-bit, -O1:
Empty for loop: 0.000000
do-while for loop: 0.000000
GCC, 32-bit, -O0:
Empty for loop: 2.633221
do-while for loop: 2.633754
GCC, 64-bit, -O0:
Empty for loop: 2.778056
do-while for loop: 2.983421 (!!!)
GCC, 32-bit, -O1:
Empty for loop: 0.000001
do-while for loop: 0.000000
GCC, 64-bit, -O1:
Empty for loop: 0.000000
do-while for loop: 0.000000