본문 바로가기

3.구현/C or C++

[C++] 콘솔입력(pipe) 성능 비교

이전에 파일 읽기 성능 비교를 해보았다. 이번에는 파일이 아닌 콘솔에서 입력하는 성능을 확인해보았다. 이는 추후 PIPE를 사용하여 확장할 수 있어서 CLI에서 꽤 유용하다.
테스트한 파일은 읽기 성능과 동일한 텍스트 파일이며 14,682,256 byte 크기이다.
운영체제는 Windows7 32bit 환경이다.

작성: http://ospace.tistory.com/,2011.12.29 (ospace114@empal.com)

결과

일단 이번에도 결과를 보자. 혹시나 했지만, 역시나 c API가 성능이 매우 좋았다.

cin의 >>연산자: 7313 msec
cin의 getline(): 813 msec
stdin과 fgets(): 349 msec

fgets()을 사용할 경우 0.35msec이고 cin은 0.8 msec 정도이다. 단순 비교로 약 2배 이상 fgets()가 빠르다. 생각보다 크게 차이가 나지 않는다(?). 주로 잘 사용했던 cin의 >> 연산자는 정말 암담하다. 사용하기는 간편하지만, 더럽게 느리다.

테스트 코드

별다른 설명 없이 코드만 나열하겠다. 샘플 코드일뿐이니 실무에서는 적당히 잘 수정해서 사용하시길 바란다.

// test_con_input.cpp : Defines the entry point for the console application.
// by ospace(2011.12.29)

#include <string>
#include <iostream>
#include <sstream>
#include <windows.h>
#include <cstdio>
#include <cstring>

using namespace std;

#define CALL_TIME(f) do {\
    DWORD start , end;\
    start = timeGetTime();\
    f();\
    end = timeGetTime();\
    std::cout &lt;&lt; #f &lt;&lt; " time: " &lt;&lt; end - start &lt;&lt; " msec" &lt;&lt; std::endl;\
} while (0)

#define LOG(m) {\
    std::ostringstream oss;\
    oss &lt;&lt; __FUNCTION__ &lt;&lt; "(" &lt;&lt; __LINE__ &lt;&lt; "): ";\
    (oss &lt;&lt; m);\
    std::cout &lt;&lt; oss.str() &lt;&lt; std::endl;\
} while(0)

void test_cin1() {
    string input;
    size_t len = 0;
    input.reserve(512);
    while (cin.good() &amp;&amp; "." != input) {
        cin &gt;&gt; input;
        //len += input.length();
    }
}

void test_cin2() {
    char buf[512] = {0,};
    while (cin.good() &amp;&amp; '.' != buf[0]) {
        cin.getline(buf, sizeof(buf));       
    }
}

void test_cin3() {
    char buf[512] = {0,};
    while (cin.good()) {
        cin.get(buf, sizeof(buf));
    }
}

void test_fgets() {
    char buf[512];
    while(!feof(stdin) &amp;&amp; 0 != strcmp(buf, ".\n")) {
        fgets(buf, sizeof(buf), stdin);

    }
}

int main(int argc, char* argv[])
{
    int idx_cin = 0;

    if (argc == 2) {
        idx_cin = atoi(argv[1]);
    }

    switch(idx_cin) {
    case 1:
        CALL_TIME(test_cin1);
        break;
    case 2:
        CALL_TIME(test_cin2);
        break;
    case 3:
        CALL_TIME(test_cin3);
        break;
    default:
        CALL_TIME(test_fgets);
        break;
    }  
    return 0;
}

결론

c++ 개발자로서 c++이 가야할 길은 멀었다. 유연성, 범용성, 그리고 성능을 동시에 잡을 수 없나?
최근 컴퓨터 성능이 좋아졌다고 하나, 어떻게 하는가에 따라서 처리되는 데이터량이 몇 배의 차이가 난다면 컴퓨터 성능 자체 문제만으로 볼 수는 없을 것이다. 물론 상황에 따라서 적절하게 취사선택해야 하지만..
그러지만, 콘솔 입력이 특수한 경우가 아니면 대용량의 데이터를 다룰 일은 거의 없기에 cin을 사용해도 무방하다고 본다. 선택은 본인이... 즐 프~~

2011.12.29.

ospace.

반응형

'3.구현 > C or C++' 카테고리의 다른 글

고급 매크로 기법 Variadic macro  (0) 2012.08.14
[C++0x] 람다식  (0) 2012.07.31
[C++] 파일 읽기 성능 비교  (0) 2011.12.28
C++ Delegate 구현원리  (2) 2011.01.17
함수호출 규약  (2) 2011.01.12