一个二进制文件里有n 个数据,我想要随机读取K个 数据,并存储在内存中。
void CDataToPyramid::CompareReadingSpeed()
{
time_t rawtime;
struct tm*timeinfo;
time(&rawtime);
timeinfo=localtime(&rawtime);
char *nowtime=asctime(timeinfo);
TCHAR Name[100];
MultiByteToWideChar(CP_ACP, 0, nowtime, -1, Name, 100);
OutputDebugString(Name);
//Sleep(3000);
int pensity=5;
float proportion=(float)pensity/10;
char *path1="D:\\Data\\ReadSpeedTest\\10_14806_132001.dat";
FILE *mfile=fopen(path1,"rb+");
if(mfile!=NULL)
{
Head head;
fread(&head,sizeof(Head),1,mfile);
int count=head.count;
int Knum=proportion*count;
CPoints *Cdata=(CPoints*)malloc(sizeof(CPoints)*Knum);
int* Iarray=new int[Knum];
ChouXi(Iarray,Knum,count);
for(int j=0;j<Knum;j++)
{
//*****测试一 随机读取 所需时间20 s
/*
int xuhao=Iarray[j];
if(j==0)
{
}
else
{
int offset=(Iarray[j]-Iarray[j-1])*sizeof(CPoints);
fseek(mfile,offset,1); //文件指针 偏移量 时间差主要消耗在这里!!!!!!!!!!!
}
CPoints Ipt;
fread(&Ipt,sizeof(CPoints),1,mfile);
memcpy((CPoints*)Cdata+j,&Ipt,sizeof(CPoints));
*/
//******测试二 顺序读取 所需时间6s
CPoints Ipt;
fread(&Ipt,sizeof(CPoints),1,mfile);
memcpy((CPoints*)Cdata+j,&Ipt,sizeof(CPoints));
}
fclose(mfile);
}
time_t rawtime1;
struct tm*timeinfo1;
time(&rawtime1);
timeinfo1=localtime(&rawtime1);
char *nowtime1=asctime(timeinfo1);
TCHAR Name1[100];
MultiByteToWideChar(CP_ACP, 0, nowtime1, -1, Name1, 100);
OutputDebugString(Name1);
MessageBox(NULL,_T("OVER"),_T("OVER"),NULL);
}
int CDataToPyramid::bigrand()
{
return RAND_MAX*rand()+rand();
}
void CDataToPyramid::ChouXi(int* cc,int K,int totalcount)
{
// 在totalcount 数中,随机产生K个不相同的数
int index=0;
if(K!=totalcount)
{
for(int i=0;K>0&&i<totalcount;i++)
{
if((bigrand()%(totalcount-i))<K)
{
cc[index]=i;
index++;
K--;
}
}
}
}