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++的执行效率基本一致。