예외를 처리하기 위해 여러가지 방법이 있는데, C++에서 표준으로 제공하는 try-throw-catch가 있다. 그러나 이 방법은 exception을 처리하기 위해 갖가지 삽질을 내부적으로 하는 것으로 매우 느리다는게 잘 알려져 있다. 그래도 얼마나 느린지 알고 싶었다. 그래서 do {} while (false)와 비교해보기로 했다.
#include <exception>
#include <iostream>
#include <sys/time.h>
using namespace std;
static size_t gTestCount(100000);
typedef long long ts_t;
ts_t
getTimestamp(void)
{
static __thread struct timeval tv;
gettimeofday(&tv, NULL);
return 1000000LL * tv.tv_sec + tv.tv_usec;
}
inline
void
funcDOWHILE(void)
{
static __thread size_t i(0);
do
{
++i;
if ( i%2 ) break;
return;
} while (false);
++i;
return;
}
inline
void
funcEXCEPTION(void)
{
static __thread size_t i(0);
static exception _e;
try
{
++i;
if ( i%2 ) throw(exception());
}
catch(const exception&)
{
++i;
}
return;
}
int
main(int argc, char* argv[])
{
ts_t t1, t2, diff;
t1 = getTimestamp();
for (size_t i(0); i<gTestCount; i++ )
{
funcEXCEPTION();
}
t2 = getTimestamp();
diff = t2 - t1;
cout << "exception: " << diff << endl;
t1 = getTimestamp();
for (size_t i(0); i<gTestCount; i++ )
{
funcDOWHILE();
}
t2 = getTimestamp();
diff = t2 - t1;
cout << "do-while: " << diff << endl;
return 0;
}
대충 컴파일해서 돌려본 결과...
exception: 492746
do-while: 250좌절인데...
물론 try-throw-catch가 함수를 넘나들 수 있는 장점은 있지만, setjmp/longjmp도 할 수 있고...
편리한 것과 속도... trade-off할만하지 않아!
Powered by ScribeFire.





덧글
rein 2007/11/29 16:12 # 답글
setjmp/longjmp와 C++ 예외 사이에는 큰 차이가 있다고 생각해서 트랙백 하나 보냅니다 ^^;
샘이 2007/11/29 16:46 # 답글
rein// 아... 저도 써놓고 뭔가 석연치 않았는데 나중에 포스팅하겠지만, 정말 setjmp/longjmp는 악마의 자식이죠. 제가 하고 싶었던 말은 꽤나 자주 일어나는 익셉션처리는 확실히 try-catch로는 너무 무거워서 하는 소립니다...