fwrite和ofstream文件輸出效率上哪個更快?

 直覺告訴我,fwrite在速度上應該會更快一些。畢竟ofstream這樣的c++輸出流,通過引入了虛函數,簡化了程

序員的編程邏輯,提高了安全性,但是也由於引入過多抽象層帶來了相應的性能開銷。

爲了佐證我的想法,特地寫了一個小程序來測試了一下,最終驗證了我的揣測。

C程序代碼如下:
#include <stdio.h>
#include <sys/time.h>
#include <time.h>

double calcPeriod( const struct timeval start, const struct timeval end )
{
    double dRate = 1e-6;
    double dStart = start.tv_sec + start.tv_usec * dRate;
    double dEnd = end.tv_sec + end.tv_usec * dRate;

    return dEnd - dStart;
}

int main()
{
    FILE * fp = fopen( "c.out", "w" );
    int i = 0;
    const char data = '1';
    const int LIMIT = 1 << 24;
    struct timeval tvStart;
    struct timeval tvEnd;
    gettimeofday( &tvStart, 0 );
    while (i < LIMIT ) {
        fwrite( &data, sizeof( data ), 1, fp );
        ++i;
    }  
    fclose( fp );
    gettimeofday( &tvEnd, 0 );

    printf( "start: %d s:%d us/n", tvStart.tv_sec, tvStart.tv_usec );
    printf( "end: %d s:%d us/n", tvEnd.tv_sec, tvEnd.tv_usec );
    printf( "%lf second passed/n", calcPeriod( tvStart, tvEnd ) );
    return 0;
}


實現相同功能的C++程序 :
#include <fstream>
#include <iostream>
#include <sys/time.h>
#include <time.h>
using namespace std;
double calcPeriod( const struct timeval& start, const struct timeval& end )
{
     double dRate = 1e-6;
     double dStart = start.tv_sec + start.tv_usec * dRate;
     double dEnd = end.tv_sec + end.tv_usec * dRate;
    
     return dEnd - dStart;
}
int main()
{
     ofstream ofs( "cxx.out" );
    
     int i = 0;
     const int LIMIT = 1 << 24;
     const char data = '1';
    
     struct timeval tvStart;
     struct timeval tvEnd;
     gettimeofday( &tvStart, 0 );
    
     while ( i < LIMIT) {
         ofs << data;
         ++i;
     }  

     ofs.close();
    
     gettimeofday( &tvEnd, 0 );
    cout << "start: " << tvStart.tv_sec << " second," << tvStart.tv_usec << " usecond" << endl;
    cout << "end: " << tvEnd.tv_sec << " second," << tvEnd.tv_usec << " usecond" <<endl;
    cout << calcPeriod( tvStart, tvEnd) << " second passed" << endl;

    return 0;
}

使用g++ -O3命令行選項編譯這兩個版本的程序,然後分別運行7次。

發現使用fwrite方式寫入16M字節文件平均需要0.754秒的時間,使用ofstream則平均耗時1.38秒。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章