为什么__try块降低了我的程序的速度

Why do __try blocks reduce speed of my program?

本文关键字:我的 程序 速度 try 为什么      更新时间:2023-10-16

我一直在研究__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;
 }

在询问问题时,您可能意味着您想使用__try/__except而不是try/catch

__try/__except是否比try/catch更快或更慢并不重要,因为,__try/__except用于捕获SEH (windows生成的错误),而不是用于捕获一般异常。

对于你写的标准c++代码,你应该总是使用try/catch,而不是__try/__except

try/catch是c++标准为处理一般c++异常所指定的。

相关文章: