为什么__try块会降低程序的速度?

时间:2011-08-15 13:04:50

标签: c++ exception

我一直在研究__try / __except构造是否足够快以供我使用,并且遇到了奇怪的结果。

我很惊讶地发现在__try块中调用函数的速度是单独调用它的两倍。

为什么会这样?


 #include <iostream>


 using namespace std;

 //addiitonal statndart includes
 #include <windows.h>

 void function()
 {
    int a=0;
        for (int i=0;i<1000;i++)
            for(int j=0;j<1000000;j++)
            {
                if(0==i*j % 2)
                    a++;
                else
                    a--;
            }
cout << a<< endl;
 }
 //you can make 0 for test wihtout try
 #define USE_TRY 1

 int main()
 {

DWORD time = 0;
time =timeGetTime();

#if USE_TRY
    __try{
        function();
    }
    __except(1)
    {
        cout <<"   exception handled"<< endl;
    }
#else
    function();
#endif

time =timeGetTime()-time;

cout<<"time = "<<time<<endl;

 }

1 个答案:

答案 0 :(得分:0)

在提出问题时,您可能意味着要使用__try / __except代替try / catch

__try / __except的工作速度是否比try / catch更快或更慢是不重要的,因为, __try / __except用于捕获 SEH (windows generated errors) ,而不是用于捕获常规异常。

对于您编写的标准C ++代码,您应始终使用try / catch而不是__try / __except

try / catch是C ++标准指定用于处理一般C ++异常的内容。