기본 콘텐츠로 건너뛰기

try { throw } catch {} & do { break } while (false)

예외를 처리하기 위해 여러가지 방법이 있는데, 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.

댓글

이 블로그의 인기 게시물

설치한 패키지에서 RPM 추출하기

오래된 패키지를 관리할 저장소가 없어졌고, 기존 패키지로 다른 서버를 세팅해야할 일이 생겼다면 RPM의 리패키지 기능을 이용해보자. $ rpm -e --repackage [PACKAGE_NAME] 위와 같이 리패키지하면, /var/spool/repackage/ 에 생성한 RPM파일이 있다. :-)

Winget 해시 무시하기

가끔씩 Winget 에서 패키지를 다운로드 했을 때, "설치 관리자 해시가 일치하지 않습니다." 오류가 뜰 때가 있다. 보안 이슈가 있지만, 그냥 무시하고 싶을 때, 아래 순서로 무시해준다. 관리자 권한 winget settings --enable InstallerHashOverride 설치 winget install --ignore-security-hash --id NirSoft.NirCmd