C和C++文本读写速度对比

C和C++文本读写速度对比

读到CSDN论坛中有一个关于C和C++文本读写速度的问题,帖子网址为http://bbs.csdn.net/topics/260005411#new_post 。网友测试结果为C语言的执行速度要优于C++,本文对此感到不太相信,于是在自己的电脑上进行了验证。验证平台是笔记本Ubuntu操作系统。g++编译,均采用O3优化等级。测试文本大小为842M。

g++ -O3 test.cpp -o test

C++方式代码如下

#include<fstream>
#include<sstream>
#include<iostream>
#include<string>

std::string file_in = "/home/xuehen/project/liblinear/featuresForEachRegion_train_0.txt";

int main(int argc,char **argv)
{
    std::ofstream ofile;
    std::ifstream ifile;
    int BuSize=1024*1024*2;
    int t1=0,t2=0;
    char* Buffer=new char[BuSize];

    ifile.open(file_in.c_str(),std::ios::in);
    ofile.open("Data2.txt",std::ios::out);

    while(!ifile.eof())
    {
        ifile.read(Buffer,BuSize);
        ofile.write(Buffer,ifile.gcount());
    }
    ifile.close();
    ofile.close();
    delete []Buffer;
    return 0;  
  }
time ./test
real    0m30.055s
user    0m0.019s
sys 0m1.794s

C语言代码如下

#include<fstream>
#include<sstream>
#include<iostream>
#include<string>

std::string file_in = "/home/xuehen/project/liblinear/featuresForEachRegion_train_0.txt";

int main(int argc,char **argv)
{
    FILE *fhr=NULL,*fhw=NULL;
    int BuSize=1024*1024*2,DataSize=0;
    int t1=0,t2=0;
    char* Buffer=new char[BuSize];

    fhr=fopen(file_in.c_str(), "r");
    fhw=fopen("Data1C.txt","w");

    while(!feof(fhr))
    {
    DataSize=fread(Buffer,sizeof(char),BuSize,fhr);
    fwrite(Buffer,sizeof(char),DataSize,fhw);
    }

    fclose(fhr);
    fclose(fhw);
    delete []Buffer;
    return 0;  
}
time ./test
real    0m32.718s
user    0m0.008s
sys 0m1.938s

从两次结果看C和C++的执行效率基本一致。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值