# CPP读取文件速度比较

竞赛中读数据的情况最多的莫过于读一大堆整数了，于是我写了一个程序，生成一千万个随机数到data.txt中，一共55MB。然后我写了个程序主干计算运行时间，代码如下：

View Code CPP
#include <ctime>
int main()
{
int start = clock();
//DO SOMETHING
printf("%.3lf\n",double(clock()-start)/CLOCKS_PER_SEC);
}

View Code CPP
const int MAXN = 10000000;

int numbers[MAXN];

{
freopen("data.txt","r",stdin);
for (int i=0;i<MAXN;i++)
scanf("%d",&numbers[i]);
}

View Code CPP
const int MAXN = 10000000;

int numbers[MAXN];

{
freopen("data.txt","r",stdin);
for (int i=0;i<MAXN;i++)
std::cin >> numbers[i];
}

View Code CPP
const int MAXN = 10000000;

int numbers[MAXN];

{
freopen("data.txt","r",stdin);
std::ios::sync_with_stdio(false);
for (int i=0;i<MAXN;i++)
std::cin >> numbers[i];
}

View Code CPP
const int MAXS = 60*1024*1024;
char buf[MAXS];

void analyse(char *buf,int len = MAXS)
{
int i;
numbers[i=0]=0;
for (char *p=buf;*p && p-buf<len;p++)
if (*p == ' ')
numbers[++i]=0;
else
numbers[i] = numbers[i] * 10 + *p - '0';
}

View Code CPP
const int MAXN = 10000000;
const int MAXS = 60*1024*1024;

int numbers[MAXN];
char buf[MAXS];

{
freopen("data.txt","rb",stdin);
buf[len] = '\0';
analyse(buf,len);
}

View Code CPP
const int MAXN = 10000000;
const int MAXS = 60*1024*1024;

int numbers[MAXN];
char buf[MAXS];

{
int fd = open("data.txt",O_RDONLY);
buf[len] = '\0';
analyse(buf,len);
}

View Code CPP
const int MAXN = 10000000;
const int MAXS = 60*1024*1024;

int numbers[MAXN];
char buf[MAXS];
void mmap_analyse()
{
int fd = open("data.txt",O_RDONLY);
int len = lseek(fd,0,SEEK_END);
char *mbuf = (char *) mmap(NULL,len,PROT_READ,MAP_PRIVATE,fd,0);
analyse(mbuf,len);
}

View Code PASCAL
const
MAXN = 10000000;
var
numbers :array[0..MAXN] of longint;
i :longint;
begin
assign(input,'data.txt');
reset(input);
for i:=0 to MAXN do
end.

Linux gcc    Windows mingw  Windows VC2008
scanf      2.010       3.704          3.425
cin	  6.380	    64.003	  19.208
cin取消同步2.050	    6.004	  19.616
mmap	  0.250	    不支持	  不支持

Linux平台上运行程序普遍比Windows上快。
Windows下VC编译的程序一般运行比MINGW（MINimal Gcc for Windows）快。
VC对cin取消同步与否不敏感，前后效率相同。反过来MINGW则非常敏感，前后效率相差8倍。
Pascal程序运行速度实在令人不敢恭维。

BYVoid原创 转载请注明

11-30 245

12-21 7478

02-11 5099

01-11 3480

11-24 470

#### c++对txt文件的读取与写入源代码

2014年08月28日 62KB 下载

04-24 6738

08-21 122

12-13 1.7万

09-07 4799