在Python函数中跟踪内存使用的来源

2024-10-06 11:39:26 发布

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

下面的函数创建一个音频分析对象,该对象本身具有 大小为64字节(根据sys.getsizeof系统),但函数本身是 为6MBmp3文件使用超过100MB的内存。你知道吗

 def main(input_filename):
     audiofile = audio.LocalAudioFile(input_filename)

我使用memory_profiler(感谢Huy Nguen)和Pympler(来自SO answer)分析了对象的大小、数量和类型(结果在下面共享)。甚至在Python中使用os.stat(input_filename)statinfo2.st_size来确认输入文件本身的大小。文件和对象的总大小看起来是11MiB(基本上是MB)。你知道吗

这是否意味着我必须深入研究创建对象的LocalAudioFile类发出的调用?如果是这样的话,那么这需要在外部模块本身的代码中完成吗,或者可以通过实验它的代码的副本来完成?你知道吗

                       types |   # objects |   total size
============================ | =========== | ============
                        dict |        2564 |      3.42 MB
                         str |       14790 |      2.43 MB
                       float |       35420 |    830.16 KB
                     unicode |        9552 |    792.63 KB
                        code |        5670 |    708.75 KB
                        list |        3160 |    606.56 KB
                        type |         484 |    427.28 KB
          wrapper_descriptor |        1658 |    129.53 KB
                       tuple |        1227 |     91.00 KB
  builtin_function_or_method |        1094 |     76.92 KB
                     weakref |         894 |     76.83 KB
           method_descriptor |         899 |     63.21 KB
                         set |         151 |     53.21 KB
           getset_descriptor |         645 |     45.35 KB
                         int |        1657 |     38.84 KB

内存分析结果:

Line #    Mem usage    Increment   Line Contents
================================================
    30   20.395 MiB    0.000 MiB   @profile
    31                             def main(input_filename, input_filename2):
    32   24.250 MiB    3.855 MiB       audiofile = audio.LocalAudioFile(input_filename) #250kb audio file
    33  139.988 MiB  115.738 MiB       audiofile2 = audio.LocalAudioFile(input_filename2) # 6MB audio file
    #irrelevant profiling code removed
    47  146.531 MiB    0.477 MiB       summary.print_(sum1)

Tags: 文件对象函数内存inputkbmaindef