零成本异常处理vs setjmp / longjmp [英] Zero cost exception handling vs setjmp/longjmp

查看:403
本文介绍了零成本异常处理vs setjmp / longjmp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个与设置恢复点相关的成本,可以这样优化一个循环:

Assuming that there is a cost associated with setting recovery point, one could optimize a loop like this:

while (doContinue) {
   try {
     doSomeWork ();
   }
   catch (...) {}
}

类似这样的:

while (doContinue) {
   try {
      do {
        doSomeWork ();
      } while (doContinue);
      break;
   } catch (...) {}
}

支持零成本异常处理,这种优化没有任何意义。

But if platform supports zero cost exception handling, this optimization does not make any sense.

有人可以告诉我如何在不同的架构上实现零成本异常处理,图什么底层机制可用于编译器/代码生成器在编译时决定是否这样优化。例如,如果可以假设 doSomeWork()没有与循环相关的副作用,编译器可以优化它?

Could someone point me out how zero cost exception handling is implemented on different architectures and is there a way to figure what underlying mechanisms are available to compiler/code generator to decide in compile-time whether to optimize like this or not. And could compiler, for example, optimize it for you if it can assume doSomeWork () has no side effects related to loop?

推荐答案

零成本方法只有在可用于目标时才可以使用。如果可用,它由最高生产质量的C ++编译器使用。否则编译器将使用 setjmp / longjmp 方法。

Zero-cost approach can be used only if available for the target in use. If available, it is used by the most production-quality C++ compilers. Otherwise compiler will use setjmp/longjmp approach.

执行速度 setjmp / longjmp 更慢。

但是,即使使用 setjmp / longjmp 机制可以导致比检查每个函数的返回代码更高的性能,如在问题中的双循环优化的示​​例。

However, even with setjmp/longjmp approach in use, using exceptions mechanism can result in higher performance than checking for return code of every function, as in example with double-loop optimization in the question.

唯一的方法来找出是否目标支持零成本方法,如果它被编译器使用是将C ++代码转换为汇编并分析它。另一种解决方案是使用 - RTS = zcx 调用 gnat ,并检查错误,如果 gnat 可用。但这不保证它将被C ++编译器使用。

The only way to find out if target supports zero-cost approach and if it is being used by compiler is to translate C++ code into assembly and analyze it. Another solution could be to invoke gnat with --RTS=zcx and check for errors, if gnat is available. But that won't guarantee that it will be used by C++ compiler.

因此,一般来说,如果程序大小不是一个问题,零成本异常可用,异常处理意外情况比检查每个函数的返回代码好得多。

So in general, if program size is not a concern and zero-cost exceptions are available, using exceptions to handle unexpected situations is much better then checking for return code of every function. Otherwise, exceptions can be used to optimize code in certain cases.

使用,但不要滥用!

> PS:我最后写了一个关于此的文章

P.S.: I ended up writing an article on this.

这篇关于零成本异常处理vs setjmp / longjmp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆