在linux下一个有趣的STL文件IO问题

在linux下读一个巨大的日志文件, 2.4G

用正文文件的方式打开, 一行一行的读

char achbuf[ 4096 ] ;

ifstream ifile( “/cygdrive/h/logs/zz/ex051117.log” ) ;

if ( !ifile ) {

cout << “error in opening” << endl ;
return -1 ;
}

int i ;

for( i = 0 ; !ifile.eof() ; i++ )
{
ifile.getline( achbuf , sizeof( achbuf ) - 1 ) ;
}
这个过程用了51秒

2.4G的文件用51秒, 47M每秒, 已经接近硬盘的最高速度了.

当时想做个尝试, 看看用二进制方式打开一次读入16M能否会更快.

char achbuf[ 4096 * 4096 ] ;
ifstream ifile( “file.log” , ios::in | ios::binary ) ;

if ( !ifile ) {

cout << “error in opening” << endl ;
return -1 ;
}

int i ;

for( i = 0 ; !ifile.eof() ; i++ )
{
ifile.read( achbuf , sizeof( achbuf ) ) ;
}
这个过程竟然用了96秒!!!!!!!!!!
到论坛请教了一下, co给出一个链接: Fast read of binary files that alternate type
试了试co推荐的文章里说的方法, 加了 ifile.imbue( std::locale::classic());, 结果为88秒, 有提高.
改用下面的代码读是54秒, 和第一个速度相近了
FILE *pfile ;

pfile = fopen( "file.log” , “rbS” ) ;

if ( pfile == NULL ) {

cout << “error in opening” << endl ;
return -1 ;
}

int i ;

for( i = 0 ; !feof( pfile ) ; i++ )
{
fread( achbuf, 1 , sizeof( achbuf ) , pfile ) ; //16M
}

fclose( pfile ) ;
刚开始学习stl,不太清楚stl文件io实现的内部机制, 不清楚为什么二进制和正文文件的读入速度差这么多.
有知道的请不吝赐教. 有能答疑解惑者,赠烤鸭一只smile_tongue

Written by oldmonk on 十月 12th, 2006 with 3 comments.
Read more articles on IT.

Tags: , , ,

Related articles

3 comments

Read the comments left by other users below, or:

引用

Get your own gravatar by visiting gravatar.com 空心人
#1. 十月 12th, 2006, at 9:10 AM.

直接用Linux的read/write呢?

[回复此评论]

引用

Get your own gravatar by visiting gravatar.com oldmonk
#2. 十月 12th, 2006, at 10:59 AM.

奇怪, 用了open, read更慢, 11x秒

[回复此评论]

引用

Get your own gravatar by visiting gravatar.com solo
#3. 十月 17th, 2006, at 11:21 PM.

要是后两种也使用4K的buffer呢?性能会有很大差别吗?

[回复此评论]

Leave your comment...

If you want to leave your comment on this article, simply fill out the next form:




  • :em10:
  • :em01:
  • :em13:
  • :em04:
  • :em05:
  • :em06:
  • :em12:
  • :em09:
  • :em07:
  • :em08:
  • :em21:
  • :em17:
  • :em33:
  • :em03:
  • :em02:
  • :em31:
  • :em34:
  • :em28:
  • :em14:
  • :em32:
  • :em36:
  • :em38:
  • :em16:
  • :em11:
  • :em18:
  • :em20:
  • :em22:
  • :em15:
  • :em19:
  • :em23:
  • :em25:
  • :em24:
  • :em29:
  • :em30:
  • :em27:
  • :em35:
  • :em26:
  • :em56:
  • :em57:
  • :em54:
  • :em37:
  • :em45:
  • :em46:
  • :em42:
  • :em39:
  • :em44:
  • :em51:
  • :em60:
  • :em43:
  • :em40:
  • :em49:
  • :em41:
  • :em47:
  • :em48:
  • :em50:
  • :em55:
  • :em58:
  • :em53:
  • :em52:
  • :em66:
  • :em64:
  • :em68:
  • :em65:
  • :em61:
  • :em59:
  • :em67:
  • :em70:
  • :em71:
  • :em62:
  • :em63:
  • :em69:
  • :em72:

You can use these XHTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> .

 
Web www.doyj.com