我做的是一个高速数据采集程序,所以对保存数据的时间有苛刻的要求。
10秒钟就有2000万个浮点型的数据,我的保存时间只允许50秒钟,也就是说我要用小于50秒钟的时间内要往txt文件里写入2000万个浮点型的数据,目前想到的是用循环法把2000万个点连成一个长度为2000万的字符串,然后一次写入长度为2000万的字符串。
遇到的问题是:写入2000万个数据太耗时间了,有没有什么批量写入数据的方法,减少循环次数,或者什么高效的写大量数据的方法?
程序如下:求高手赐教
#include<stdio.h>
#include<afx.h>
#define TOTAL 10
void WriteData(CString,double *);
double data[TOTAL];
void main()
{
long i,a=1;
for(i=1;i<=TOTAL;i++)
{
data[i]=i;
printf("data=%f\n",data[i]);
}
WriteData("D:\\log.txt",data);
}
void WriteData(CString strPath,double * q)//写文件的函数
{
// 1 Open the file and move pointer to the end of the file
CStdioFile pFile;
pFile.Open(strPath,CFile::modeWrite | CFile::typeText | CFile::modeCreate | CFile::modeNoTruncate);
pFile.SeekToEnd();
// 2 Write current time and the name of the current model
CString s;
s = CTime::GetCurrentTime().Format("\n%m-%d-%Y %H:%M:%S\ndata:\n");
CString temp;
// 3 Write the digits, each in a row
for(long i = 0 ; i <TOTAL; i ++)
{
temp.Format("%f\n",q[i]);
s += temp;
}
//write entire string at one time
pFile.WriteString(s);
pFile.Close();
}
数据卡是10秒钟采集了2000万个浮点数据后,自动保存到我自己C语言创建的数组中,我要做的就是用小于50秒的时间把 数组中2000万个浮点数据写到txt文本上。1楼说不要存字符串,直接存数据,是什么意思?是把浮点型的数据以机器码的形式保存在txt文件中吗?
//没啥高科技,编译release,这个2000万也就消耗我9秒不到
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <time.h>
//如果你用的是VC6,这个宏对于习惯标准语法的人很管用
#define for if(false);else for
// lpszFilePath 文件名
// pData 浮点数数组
// iLength 浮点数个数
void writeData(const char * const lpszFilePath, const double * const pData, const int iLength)
{
int iFileSize=0;
FILE *pFile=fopen(lpszFilePath,"w");
assert(pFile!=NULL);
//申请32MB的缓冲
char * const pBuffer=(char *)malloc(1024*1024*32);
assert(pBuffer!=NULL);
char * const pBufferEnd=pBuffer+1024*1024*32-100;
char * pCurrent=pBuffer;
for (int i=0;i<iLength;i++)
{
if(pCurrent>=pBufferEnd)
{
fwrite(pBuffer,pCurrent-pBuffer,1,pFile);
pCurrent=pBuffer;
}
pCurrent+=sprintf(pCurrent,"%e",pData[i]);
pCurrent[0]='\n';
pCurrent++;
}
fwrite(pBuffer,pCurrent-pBuffer,1,pFile);
fclose(pFile);
free(pBuffer);
}
int main()
{
clock_t start, finish;
start=clock();
double *a=new double[20000000];
writeData("c:\\1.txt",a,20000000);
finish=clock();
printf("消耗时间:%.2f 秒", (double)(finish-start)/CLOCKS_PER_SEC );
delete[] a;
return 0;
}