python中的高效内存使用

2024-10-02 08:24:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个Python脚本,使用pyodbc将数据从excel表传输到msaccess,还使用matplotlib来使用excel表中的一些数据来创建绘图并将其保存到文件夹中。当我运行这个脚本时,它做了我期望它做的事情;但是,我用任务管理器监视它,结果它使用了超过1500 MB的RAM!在

我甚至不明白这怎么可能。它创建了560个图像,但是这些图像的总大小只有17MB。excel工作表为8.5 MB。我明白也许你不能在没有看到我所有代码的情况下确切地告诉我问题出在哪里(我不知道到底是什么问题,所以我只需要发布整个代码,我认为让你阅读我的整个代码是不合理的),但是一些一般的指导原则就足够了。在

谢谢。在

更新

我照@HYRY的建议做了,把我的代码分开了。我首先只使用matplotlib函数运行脚本,然后没有使用它们。正如到目前为止发表评论的人所怀疑的那样,内存占用来自matplotlib函数。现在我们已经缩小了范围,我将发布我的一些代码。请注意,下面的代码在两个for循环中执行。内部for循环将始终执行四次,而外部for循环将执行多次。在

#Plot waveform and then relative harmonic orders on a bar graph.
#Remember that table is the sheet name which is named after the ExperimentID
cursorEx.execute('select ['+phase+' Time] from ['+table+']')
Time = cursorEx.fetchall()                   
cursorEx.execute('select ['+phase+' Waveform] from ['+table+']')
Current = np.asanyarray(cursorEx.fetchall())                                                               
experiment = table[ :-1]                
plt.figure()
#A scale needs to be added to the primary current values
if line == 'P':
    ratioCurrent = Current / 62.5
    plt.plot(Time, ratioCurrent)
else:
    plt.plot(Time, Current)
plt.title(phaseTitle)
plt.xlabel('Time (s)')
plt.ylabel('Current (A)')
plt.savefig(os.getcwd()+'\\HarmonicsGraph\\'+line+'H'+experiment+'.png')

cursorEx.execute('select ['+phase+' Order] from ['+table+']')
cursorEx.fetchone() #the first row is zero
order = cursorEx.fetchmany(51)
cursorEx.execute('select ['+phase+' Harmonics] from ['+table+']')
cursorEx.fetchone()
percentage = np.asanyarray(cursorEx.fetchmany(51))

intOrder = np.arange(1, len(order) + 1, 1)  
plt.figure()                
plt.bar(intOrder, percentage, width = 0.35, color = 'g')                
plt.title(orderTitle)
plt.xlabel('Harmonic Order')
plt.ylabel('Percentage')
plt.axis([1, 51, 0, 100])
plt.savefig(os.getcwd()+'\\HarmonicsGraph\\'+line+'O'+experiment+'.png')

Tags: the代码from脚本forexecutetimematplotlib
2条回答

我认为plt.关闭()是一个非常困难的解决方案,当您要在脚本中绘制多个绘图时。很多时候,如果保留地物参照,则可以对其执行所有操作,并在调用之前调用:

plt.clf() 

您将看到您的代码是如何更快的(与每次生成画布不同!)。内存泄漏是可怕的,当你调用多个轴o图形没有适当的清洁!在

我在你的代码中看不到清理部分,但我敢打赌问题是你没有调用

plt.close()

在你完成每一个情节之后。在完成每个图形后添加一行,看看是否有用。在

相关问题 更多 >

    热门问题