异常与错误码的性能对比

今天看到一篇文章说,在没有抛出异常的情况下,使用异常比使用错误码更快。
有点好奇,打算测试了一下。

我们定义一个函数 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 来传递错误码,会有什么变化呢?感兴趣的朋友可以研究一下。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值