기본 콘텐츠로 건너뛰기

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.

댓글

이 블로그의 인기 게시물

탐색기에서 OneDrive 이 2개로 보이는 문제

왜 2개가 보이는지 모르겠지만, Registry 삭제하면 됨 HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace 하위 키에서 OneDrive 둘 중에 하나만 지워도 바로 반영됨. 참조:  https://answers.microsoft.com/en-us/msoffice/forum/all/duplicate-onedrives-in-file-explorer/49c935a6-287b-43a5-aed5-2dee2a1c1b22