#include “iostream”
#include “fcntl.h”
#include “ctime”
#include “stdio.h”
#include “fstream”
#include <sys/mman.h>
using namespace std;
#define MAXNUM 5000000
#define MAXCHAR 50*1024*1024
static int num[MAXNUM];
char buf[MAXCHAR]; //近50m的文件
/*读入的字符串转换成数组*/
void analyse(char *buf,int len)
{
int i = 0;
num[i] = 0;
for(char *p = buf; *p && p-buf < len; p++)
{
if((*p == ‘ ‘) == 1)
{
num[++i] = 0;
}
else
{
num[i] = num[i]*10 + *p – ’0′;
}
}
cout<<” Processed “<<i<<endl;
return;
}
int main()
{
int start,i;
FILE *fp;
/*fread 共用时:0.33s */
start = clock();
if((fp = freopen(“big.txt”,”r”,stdin)) == NULL)
{
cout<<”Error to open big.txt”<<endl;
return 1;
}
int len = fread(buf,1,MAXCHAR,stdin);
buf[len] = ”;
analyse(buf,len);
double end = double(clock()-start)/CLOCKS_PER_SEC;
cout<<”1. fread Using time : “<<end<<endl;
fclose(fp);
/*read 共用时:0.01s */
start = clock();
int fd = open(“big.txt”,O_RDONLY);
len = read(fd,buf,MAXCHAR);
buf[len] = ”;
end = double(clock()-start)/CLOCKS_PER_SEC;
analyse(buf,len);
cout<<”2. read Using time : “<<end<<endl;
fclose(fp);
/*mmap 共用时:0.29s */
start = clock();
fd = open(“big.txt”,O_RDONLY);
len = lseek(fd,0,SEEK_END);
char *mbuf = (char*)mmap(NULL,len,PROT_READ,MAP_PRIVATE,fd,0);
analyse(mbuf,len);
end = double(clock()-start)/CLOCKS_PER_SEC;
cout<<”3. mmap Using time : “<<end<<endl;
fclose(fp);
/*fgets 共用时:0.28s */
start = clock();
fp = fopen(“big.txt”,”r”);
fgets(buf,MAXCHAR,fp);
analyse(mbuf,len);
end = double(clock()-start)/CLOCKS_PER_SEC;
cout<<”5.fgets Using time : “<<end<<endl;
fclose(fp);
/*ifstream.get 共用时:0.42s */
start = clock();
ifstream fsg(“big.txt”);
fsg.get(buf,MAXCHAR);
analyse(buf,len);
end = double(clock()-start)/CLOCKS_PER_SEC;
cout<<”6.ifstream.get Using time : “<<end<<endl;
fsg.close();
/*ifstream.read 用时:0.27s*/
start = clock();
ifstream fs(“big.txt”);
fs.read(buf,MAXCHAR);
analyse(buf,len);
end = double(clock()-start)/CLOCKS_PER_SEC;
cout<<”4.fstream.read using time: “<<end<<endl;
fs.close();
return 0;
}