在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給出一個鏈接: 
試了試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 ) ;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章