fgets vs ifstream::getline 성능비교

aswip의 이미지

다음은 파일로부터 한줄 한줄 읽어들이는 방법에 대해서 구현한 두가지 유형입니다.

* fgets 테스트 코드 (표준 stdio)

FILE *fp = fopen("c:\\1.txt", "rb" );
char szLine[4096]={0};
while ( fgets(szLine, 4096, fp) );
fclose(fp);

* getline 테스트 코드 (표준 iostream)

ifstream fs;
char szLine[4096]={0};
fs.open("c:\\1.txt", ios::in | ios::binary);
while ( fs.getline(szLine, 4096) );
fs.close();


그리고 다음은, 위의 두가지 유형의 방법을 사용하여, 테스트 한 결과입니다.

* 테스트 파일의 크기 : 5,043kb ( 약 5메가 )
* 반복횟수 : 50 번
* 수행 결과 ( 50번을 수행한 평균치 : 단위 ms )

- fgets elapsed time 6690 ms
- getline Elapsed time 280 ms

테스트 초반에 예상하기론, 어느쪽이 우세하든 그 차이는거의 미비할 거라
짐작했으나, 예상을 완전히 빗나가버린 테스트였습니다. ^^;;

혹시, 제가 fgets를 잘못 사용하고 있는건 아닌지,
그리고 ifstream::getline() 메소드 보다 좀 더 효율적인 방법은 없는지
궁금합니다. :D

익명 사용자의 이미지

차이가 너무 심한데요? 혹시 최적화 때문일지도 모르니, 중간에다가 다음 코드를 집어넣어 보는 것은 어떻습니까?

unsigned t = 0;
while ( fs.getline(szLine, 4096) ) { t += szLine[10]; }

익명 사용자의 이미지

그리고, 디스크 캐쉬 때문일지도 모르니 두개를 교대로 실행해서 결과를 봤으면 좋겠군요. 1, 2, 1, 2... 이런식으로...

aswip의 이미지

Anonymous wrote:
차이가 너무 심한데요? 혹시 최적화 때문일지도 모르니, 중간에다가 다음 코드를 집어넣어 보는 것은 어떻습니까?

unsigned t = 0;
while ( fs.getline(szLine, 4096) ) { t += szLine[10]; }

결과는 동일합니다. :D

- 인생은 스스로 -

aswip의 이미지

Anonymous wrote:
그리고, 디스크 캐쉬 때문일지도 모르니 두개를 교대로 실행해서 결과를 봤으면 좋겠군요. 1, 2, 1, 2... 이런식으로...

말씀하신 띄엄 띄엄 테스트를 해보기도 하고, 어느 한가지 유형을 50번 반복하기도 하였지만, 결과는 동일합니다. 제 pc 만 그런건 아닐것 같은데, 혹시 테스트 해보셨나요 :?: :D

- 인생은 스스로 -

익명 사용자의 이미지

1.c:

#include <stdio.h>
#include <time.h>

int main(void)
{
        time_t t1, t2;
        char szLine[4096]={0};
        unsigned t;
        int i;
        FILE *fp;
        t1 = time(0);
        fp = fopen("m", "rb");
        while ( fgets(szLine, 4096, fp) )
        {
                for ( i = 0; i < 4096; ++i ) { t += szLine[i]; }
        }
        fclose(fp);
        t2 = time(0);
        printf("%lf\n", difftime(t2, t1));
        return 0;
}

2.cc:

#include <ctime>
#include <iostream>
#include <fstream>

using namespace std;

int main(void)
{
        time_t t1, t2;
        char szLine[4096]={0};
        unsigned t;
        int i;
        ifstream fs;
        t1 = time(0);
        fs.open("m", ios::in | ios::binary);
        while ( fs.getline(szLine, 4096) )
        {
                for ( i = 0; i < 4096; ++i ) { t += szLine[i]; }
        }
        fs.close();
        t2 = time(0);
        cout << difftime(t2, t1) << endl;
        return 0;
}

gcc 버젼

gcc (GCC) 3.3.5-20050130 (Gentoo 3.3.5.20050130-r1, ssp-3.3.5.20050130-1, pie-8.7.7.1)
Copyright (C) 2003 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

8메가바이트 텍스트 파일로 실험한 결과 1번은 10초, 10초, 10초가 나왔고 2번은 12초, 12초, 12초가 나왔습니다. 물론 실행순서는 1,2,1,2,1,2였고요.

익명 사용자의 이미지

위의 프로그램으로 다시 한번 결과를 확인해 보시길 바랍니다.

aswip의 이미지

Anonymous wrote:
위의 프로그램으로 다시 한번 결과를 확인해 보시길 바랍니다.

이전과는 다르게, fgets()과, getline()보다 더 빠르게 동작함을 확인하였습니다. ^^

- 인생은 스스로 -

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.