我正在尝试运行一个程序来分析一堆包含数字的文本文件。文本文件的总大小约为 12 MB,我从 360 个文本文件中的每个文件中提取 1,000 个双精度并将它们放入一个向量中。我的问题是我在文本文件列表中完成了大约一半,然后我的计算机速度变慢,直到它不再处理任何文件。该程序不是无限循环,但我认为我有使用太多内存的问题。有没有更好的方法来存储不会使用太多内存的数据?
其他可能相关的系统信息:
运行 Linux
8 GB 内存
安装了 Cern ROOT 框架(虽然我不知道如何减少我的内存占用)
英特尔至强四核处理器
如果您需要其他信息,我将更新此列表
编辑:我跑了 top,我的程序使用了更多的内存,一旦它超过 80%,我就杀了它。有很多代码,所以我会挑选出分配内存的位以便共享。编辑2:我的代码:
void FileAnalysis::doWork(std::string opath, std::string oName)
{
//sets the ouput filepath and the name of the file to contain the results
outpath = opath;
outname = oName;
//Reads the data source and writes it to a text file before pushing the filenames into a vector
setInput();
//Goes through the files queue and analyzes each file
while(!files.empty())
{
//Puts all of the data points from the next file onto the points vector then deletes the file from the files queue
readNext();
//Places all of the min or max points into their respective vectors
analyze();
//Calculates the averages and the offset and pushes those into their respective vectors
calcAvg();
}
makeGraph();
}
//Creates the vector of files to be read
void FileAnalysis::setInput()
{
string sysCall = "", filepath="", temp;
filepath = outpath+"filenames.txt";
sysCall = "ls "+dataFolder+" > "+filepath;
system(sysCall.c_str());
ifstream allfiles(filepath.c_str());
while (!allfiles.eof())
{
getline(allfiles, temp);
files.push(temp);
}
}
//Places the data from the next filename into the files vector, then deletes the filename from the vector
void FileAnalysis::readNext()
{
cout<<"Reading from "<<dataFolder<<files.front()<<endl;
ifstream curfile((dataFolder+files.front()).c_str());
string temp, temptodouble;
double tempval;
getline(curfile, temp);
while (!curfile.eof())
{
if (temp.size()>0)
{
unsigned long pos = temp.find_first_of("\t");
temptodouble = temp.substr(pos, pos);
tempval = atof(temptodouble.c_str());
points.push_back(tempval);
}
getline(curfile, temp);
}
setTime();
files.pop();
}
//Sets the maxpoints and minpoints vectors from the points vector and adds the vectors to the allmax and allmin vectors
void FileAnalysis::analyze()
{
for (unsigned int i = 1; i<points.size()-1; i++)
{
if (points[i]>points[i-1]&&points[i]>points[i+1])
{
maxpoints.push_back(points[i]);
}
if (points[i]<points[i-1]&&points[i]<points[i+1])
{
minpoints.push_back(points[i]);
}
}
allmax.push_back(maxpoints);
allmin.push_back(minpoints);
}
//Calculates the average max and min points from the maxpoints and minpoints vector and adds those averages to the avgmax and avgmin vectors, and adds the offset to the offset vector
void FileAnalysis::calcAvg()
{
double maxtotal = 0, mintotal = 0;
for (unsigned int i = 0; i<maxpoints.size(); i++)
{
maxtotal+=maxpoints[i];
}
for (unsigned int i = 0; i<minpoints.size(); i++)
{
mintotal+=minpoints[i];
}
avgmax.push_back(maxtotal/maxpoints.size());
avgmin.push_back(mintotal/minpoints.size());
offset.push_back((maxtotal+mintotal)/2);
}
编辑 3:我添加了代码以保留向量空间,并添加了关闭文件的代码,但在程序停止之前我的内存仍然填充到 96%...