python - python 中的高效内存使用

标签 python memory-management matplotlib pyodbc

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

我什至不明白这怎么可能。它创建了 560 个图像,但这些图像的总大小仅为 17 MB。 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')

最佳答案

我认为当您在脚本中执行多个绘图时,plt.close() 是一个非常困难的解决方案。很多时候,如果保留图形引用,则可以对它们进行所有工作,之前调用:

plt.clf() 

您将看到您的代码如何更快(与每次生成 Canvas 都不一样!)。当您在没有适当清理的情况下调用多个轴或图形时,内存泄漏是可怕的!

关于python - python 中的高效内存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15682863/

相关文章:

ios - IOS7和 "Terminated due to Memory Pressure"中的内存管理

python - matplotlib 表中的粗体文本

python - 无法在 matplotlib 中使用自定义字体

python - 3D 散点图颜色条 matplotlib Python

python - google-cloud 使用 python api 获取实例 ID 和区域

python - 将 Django OAuth2 提供程序与 JupyterHub 结合使用

python - 如何将梅尔频谱图转换为对数缩放梅尔频谱图

C++ 基于栈的对象分配

python - 如何在 jinja2 中对危险的未经处理的输入进行 html 转义?

c - 需要帮助解决由Game Maker语言重写动态内存分配器(最初为C)引起的最后几个非bug的“怪胎”