首页 > 文章列表 > 监控 Python 内存使用情况和代码执行时间

监控 Python 内存使用情况和代码执行时间

Python 内存 开发
465 2023-05-01

我的代码的哪些部分运行时间最长、内存最多?我怎样才能找到需要改进的地方?

在开发过程中,我很确定我们大多数人都会想知道这一点,在本文中总结了一些方法来监控 Python 代码的时间和内存使用情况。

本文将介绍4种方法,前3种方法提供时间信息,第4个方法可以获得内存使用情况。

  • time 模块
  • %%time 魔法命令
  • line_profiler
  • memory_profiler

time 模块

这是计算代码运行所需时间的最简单、最直接(但需要手动开发)的方法。他的逻辑也很简单:记录代码运行之前和之后的时间,计算时间之间的差异。这可以实现如下:

%%time 魔法命令魔法命令是IPython内核中内置的方便命令,可以方便地执行特定的任务。一般情况下都实在jupyter notebook种使用。在单元格的开头添加%%time ,单元格执行完成后,会输出单元格执行所花费的时间。%%time
 def convert_cms(cm, unit='m'):
 '''
Function to convert cm to m or feet
'''
 if unit == 'm':
 return cm/100
 return cm/30.48
 
 convert_cms(1000)

结果如下:

line_profiler前两个方法只提供执行该方法所需的总时间。通过时间分析器我们可以获得函数中每一个代码的运行时间。这里我们需要使用line_profiler包。使用pip install line_profiler。import line_profiler
 
 def convert_cms(cm, unit='m'):
 '''
Function to convert cm to m or feet
'''
 if unit == 'm':
 return cm/100
 return cm/30.48
 
 # Load the profiler
 %load_ext line_profiler
 
 # Use the profiler's magic to call the method
 %lprun -f convert_cms convert_cms(1000, 'f')

输出结果如下:

memory_profiler与line_profiler类似,memory_profiler提供代码的逐行内存使用情况。要安装它需要使用pip install memory_profiler。我们这里监视convert_cms_f函数的内存使用情况。from conversions import convert_cms_f
 import memory_profiler
 
 %load_ext memory_profiler
 
 %mprun -f convert_cms_f convert_cms_f(1000, 'f')

convert_cms_f函数在单独的文件中定义,然后导入。结果如下:

Line # Mem usage Increment Occurrences Line Contents
 =============================================================
1 63.7 MiB 63.7 MiB 1 def convert_cms_f(cm, unit='m'):
2 '''
3 Function to convert cm to m or feet
4 '''
5 63.7 MiB 0.0 MiB 1 if unit == 'm':
6 return cm/100
7 63.7 MiB 0.0 MiB 1 return cm/30.48

memory_profiler 提供对每行代码内存使用情况的详细了解。

这里的1 MiB (MebiByte) 几乎等于 1MB。1 MiB  = 1.048576 1MB

但是memory_profiler 也有一些缺点:它通过查询操作系统内存,所以结果可能与 python 解释器略有不同,如果在会话中多次运行 %mprun,可能会注意到增量列报告所有代码行为 0.0 MiB。这是因为魔法命令的限制导致的。

虽然memory_profiler有一些问题,但是它就使我们能够清楚地了解内存使用情况,对于开发来说是一个非常好用的工具。

总结

虽然Python并不是一个以执行效率见长的语言,但是在某些特殊情况下这些命令对我们还是非常有帮助的。