主题:求问如何加快从文件读取大量数据到数组的速度
代码如下,查找和排序的头文件我没加进来,一般运行要7秒,测试了下,把每行数据写进数组就要6.5秒,主要是那个for循环耗时,求问如何改进!
[code=c]
#include<ctime>
#include<iostream>
#include<fstream>
#include"qck.h"
#include"binarysearch.h"
using namespace std;
int main()
{
char filename[20];
cout<<"请输入文件名:";
cin>>filename;
ifstream infile(filename,ios::in);
if(!infile)
{
cerr<<"open error!"<<endl;
exit(1);
}
clock_t start,finish;//声明开始结束变量
start=clock();//开始计算时间
char x[8];
infile.getline(x,8,'\n');
int *b;
b=new int[sizeof(int)*1000000];
int i;
for(i=0;i<1000000;i++)
{
infile.getline(x,8,'\n');
b=atoi(x);
}
qck(b,1000000);
cout<<"top 3:"<<endl;
for(i=0;i<3;i++)
cout<<b<<endl;
cout<<endl;
cout<<"last 3:"<<endl;
for(i=999997;i<1000000;i++)
cout<<b<<endl;
cout<<endl;
int num;
num=binarysearch(b,1000000,856509);
cout<<"index of 856509:"<<num<<endl;
cout<<"data of index 223731:"<<b[223730]<<endl;
finish=clock();//结束计算时间
cout<<endl<<"程序所用时间:"<<(double)(finish-start)/CLK_TCK<<"s"<<endl;//输出时间
return 0;
} [/code]
[code=c]
#include<ctime>
#include<iostream>
#include<fstream>
#include"qck.h"
#include"binarysearch.h"
using namespace std;
int main()
{
char filename[20];
cout<<"请输入文件名:";
cin>>filename;
ifstream infile(filename,ios::in);
if(!infile)
{
cerr<<"open error!"<<endl;
exit(1);
}
clock_t start,finish;//声明开始结束变量
start=clock();//开始计算时间
char x[8];
infile.getline(x,8,'\n');
int *b;
b=new int[sizeof(int)*1000000];
int i;
for(i=0;i<1000000;i++)
{
infile.getline(x,8,'\n');
b=atoi(x);
}
qck(b,1000000);
cout<<"top 3:"<<endl;
for(i=0;i<3;i++)
cout<<b<<endl;
cout<<endl;
cout<<"last 3:"<<endl;
for(i=999997;i<1000000;i++)
cout<<b<<endl;
cout<<endl;
int num;
num=binarysearch(b,1000000,856509);
cout<<"index of 856509:"<<num<<endl;
cout<<"data of index 223731:"<<b[223730]<<endl;
finish=clock();//结束计算时间
cout<<endl<<"程序所用时间:"<<(double)(finish-start)/CLK_TCK<<"s"<<endl;//输出时间
return 0;
} [/code]