C/C++ 读文件方式类比
来源:互联网 发布:三星oculus 软件下载 编辑:程序博客网 时间:2024/05/01 02:23
#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;
}
- C/C++ 读文件方式类比
- 学习C与Java的类比
- c#-以二进制方式读文件
- 【C语言】C\C++ 文件打开方式
- [C/C++]读取文件的多种方式
- C方式的文件操作
- C文件操作中的方式
- C语言文件打开方式
- c语言文件读写方式
- c语言文件读写方式
- C语言 文件打开方式
- c语言打开文件方式
- C语言文件打开方式
- 【C语言】文件打开方式
- Python中的变量解析(类比C语言)
- Python中的字典与C语言中的switch结构类比
- 类比C#、JavaScript和Java的集合数据处理
- Android 非NDK方式编译C文件
- java web项目中上传文件、图片路径问题
- 如何查看Class文件编译的JDK版本
- ListView的异步加载图片
- MFC如何使用自己画的光标
- 使用Latex编辑你的论文 傻瓜版
- C/C++ 读文件方式类比
- eclipe + GoogleCode 管理代码
- Windows 7下:应用程序无法正常启动(0xc0150002)
- Xmanager3连接RedHat5
- 【第六章】 AOP 之 6.1 AOP基础 ——跟我学spring3
- 【第六章】 AOP 之 6.2 AOP的HelloWorld ——跟我学spring3
- Cocos2d中CCSpriteBatchNode与纹理贴图集(Texture Atlas)的作用
- 遍历Map集合的三种方法
- Struts2中的struts.multipart.saveDir的配置