今天看到一篇文章说,在没有抛出异常的情况下,使用异常比使用错误码更快。
有点好奇,打算测试了一下。
我们定义一个函数 f ,正常情况下返回一个整数。然后反复调用这个函数,统计总时长。
首先测试使用异常的情况。在这个函数里,特定条件下抛出异常。并且在主函数中捕获异常。
#include <stdio.h>
#include <time.h>
int condition;
int f(){
int r;
if (condition == 1) {
throw 1;
} else {
return 1;
}
}
int main(){
clock_t start_time = clock();
for (int i = 0; i < 200000000; i++) {
try {
int r = f();
}
catch(...) {
printf("failed\n");
}
}
clock_t end_time = clock();
printf("total time: %ld\n", end_time - start_time);
return 0;
}
编译一下,多次执行:
0|gaory@newbook::~$ g++ exception.cpp
0|gaory@newbook::~$ ./a.out
total time: 346544
0|gaory@newbook::~$ ./a.out
total time: 349619
0|gaory@newbook::~$ ./a.out
total time: 348466
0|gaory@newbook::~$ ./a.out
total time: 349111
0|gaory@newbook::~$ ./a.out
total time: 347389
0|gaory@newbook::~$ ./a.out
total time: 346196
0|gaory@newbook::~$ ./a.out
total time: 347645
0|gaory@newbook::~$ ./a.out
total time: 343169
0|gaory@newbook::~$ ./a.out
total time: 335775
0|gaory@newbook::~$ ./a.out
total time: 345367
再来测试一下使用错误码的情况。这里我们通过返回值传递错误码。
#include <stdio.h>
#include <time.h>
int condition;
typedef struct {
int value;
int err;
} Result;
Result f(){
Result r;
if (condition == 1) {
r.value = 0;
r.err = 1;
return r;
} else {
r.value = 1;
r.err = 0;
return r;
}
}
int main(){
clock_t start_time = clock();
for (int i = 0; i < 200000000; i++) {
Result r = f();
if (r.err != 0) {
printf("failed\n");
}
}
clock_t end_time = clock();
printf("total time: %ld\n", end_time - start_time);
return 0;
}
执行:
0|gaory@newbook::~$ g++ error_code.cpp
0|gaory@newbook::~$ ./a.out
total time: 1187814
0|gaory@newbook::~$ ./a.out
total time: 1184911
0|gaory@newbook::~$ ./a.out
total time: 1185881
0|gaory@newbook::~$ ./a.out
total time: 1189657
0|gaory@newbook::~$ ./a.out
total time: 1178753
0|gaory@newbook::~$ ./a.out
total time: 1190077
0|gaory@newbook::~$ ./a.out
total time: 1196612
0|gaory@newbook::~$ ./a.out
total time: 1191935
0|gaory@newbook::~$ ./a.out
total time: 1190060
0|gaory@newbook::~$ ./a.out
total time: 1194021
可以看到,使用异常确实明显比使用错误码更快。
如果我们用 errno 来传递错误码,会有什么变化呢?感兴趣的朋友可以研究一下。