我认为使用过多的内存

如何解决我认为使用过多的内存

| 我正在尝试运行一个程序来分析一堆包含数字的文本文件。文本文件的总大小约为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)。 如果那还不足以解决问题,请在必要的位置添加更多详细的日志记录,并/或闯入调试器并开始跟踪(当您的代码概念与计算机不同时,这很有用,我们经常阅读我们认为的代码)而不是实际说的话)。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res