我认为使用过多的内存

问题描述

| 我正在尝试运行一个程序来分析一堆包含数字的文本文件。文本文件的总大小约为12 MB,我从360个文本文件中分别提取了1000倍,并将其放入向量中。我的问题是我进入了文本文件列表的一半,然后我的计算机速度变慢,直到不再处理任何文件。该程序不是无限循环,但我认为使用过多内存存在问题。有没有更好的方法来存储不会占用太多内存的数据? 其他可能相关的系统信息: 运行Linux 8 GB内存 已安装Cern ROOT框架(不过,我不知道如何减少内存占用) 英特尔至强四核处理器 如果您需要其他信息,我将更新此列表 编辑:我跑了顶,我的程序使用更多的内存,并且一旦它超过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%。     

解决方法

        可以无休止地进行优化,但是我的直接反应是使用除vector之外的其他容器。请记住,向量的存储是在内存中按顺序分配的,这意味着如果没有足够的当前空间来容纳新元素,则添加其他元素会导致整个向量的重新分配。 请尝试针对常量插入进行优化的容器,例如队列或列表。 或者,如果需要向量,则可以尝试预先分配预期的内存占用以避免连续重新分配。参见
vector.reserve()
:向量。请注意,保留的容量以元素而不是字节为单位。
int numberOfItems = 1000;
int numberOfFiles = 360;

size_type totalExpectedSize = (numberOfItems) * (numberOfFiles);
myVector.reserve( totalExpectedSize );
----------编辑以下代码后---------- 我直接关心的是“ 3”中的以下逻辑:
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); 
具体来说,我关心的是allmax和allmin容器,要将maxpoint和minpoint容器的副本推送到这些容器上。根据数据集,使用此逻辑,maxpoints和minpoints容器本身可以变得非常大。 您要承担数倍的容器复制费用。是否真的有必要将minpoints / maxpoints容器复制到allmax / allmin中?一无所知,很难优化您的存储设计。 我看不到最小点和最大点实际上被清空的任何地方,这意味着随着时间的推移它们会变得非常大,并且它们对应于allmin / allmax容器的副本也会变得非常大。最小点/最大点是否应该代表一个文件的最小/最大点? 作为示例,让我们看一下简化的最小点和allmin方案(但请记住,这同样适用于max,并且两者都比此处显示的范围更大)。显然,这是一个旨在说明我观点的数据集:
File 1: 2 1 2 1 2 1 2 1 2 1 2
minpoints: [1 1 1 1 1]
allmin:    [1 1 1 1 1]

File 2: 3 2 3 2 3 2 3 2 3 2 3
minpoints: [1 1 1 1 1 2 2 2 2 2]
allmin:    [1 1 1 1 1 1 1 1 1 1 2 2 2 2 2]

File 3: 4 3 4 3 4 3 4 3 4 3 4
minpoints: [1 1 1 1 1 2 2 2 2 2 3 3 3 3 3]
allmin:    [1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3]
还有其他优化和批评,但是现在我将其限制为试图解决您的紧迫问题。可以发布
makeGraph()
函数以及所有涉及的容器的定义(点,最小点,最大点,allmin,allmax)吗?     ,        一些尝试: 运行ѭ7,查看程序正在使用多少内存。 在
valgrind
下运行一个较小的问题示例(例如,从1个文件读取10个浮点数)并检查内存泄漏。 使用ѭ9预先分配所需向量的大小(高估)     ,         检查内存使用情况是否符合您的期望。您没有泄漏资源(您是否无法释放任何内存,无法关闭任何文件?) 尝试预先将向量保留为所需的完整大小,然后查看其分配是否正确。 您是否需要一次将所有结果存储在内存中?您可以将它们写到文件中吗? 如有必要,您可以尝试: 使用小于double的数据类型 使用数组(如果您担心开销)而不是向量 如果您担心内存碎片,请使用向量的链接列表 但这并不是必须的(或会产生影响),正如我同意的那样,您正在做的事情听起来应该可行。     ,查看您的代码和迭代次数。如果您进行了如此多的迭代而没有进行睡眠或基于事件的编程,则您的过程可能会消耗大量CPU。 要么 预先为vector分配元素数量,这样就无需重新分配vector。 由于大多数程序消耗CPU,因此请在后台运行进程并使用top命令查看程序的CPU和内存使用情况。     ,        您可能会在
readNext()
方法中使用
eof()
遇到问题。例如,请参阅此SO问题和C ++ FAQ中的15.4 / 15.5节。如果确实是这个问题,那么固定读取循环以检查
getline()
的返回状态应该可以解决此问题。 如果没有,我将从调试开始看程序在哪里/如何“崩溃”。在这种情况下,我可能首先通过simple13ѭ简单地记录到控制台或日志文件,然后每隔1000行开始输出当前文件和状态。让它运行几次并检查日志输出中是否有任何明显的故障迹象(即,它永远不会越过读取文件#3)。 如果那还不足以解决问题,请在必要的位置添加更多详细的日志记录,并/或闯入调试器并开始跟踪(当您的代码概念与计算机不同时,这很有用,我们经常阅读我们认为的代码)而不是实际说的话)。