擅长:python、mysql、java
<p>使用<a href="https://pypi.python.org/pypi/memory_profiler" rel="noreferrer">memory_profiler</a>可以做到这一点。函数<code>memory_usage</code>返回一个值列表,这些值表示一段时间内的内存使用情况(默认情况下为.1秒)。如果你需要最大值,就取列表中的最大值。小例子:</p>
<pre><code>from memory_profiler import memory_usage
from time import sleep
def f():
# a function that with growing
# memory consumption
a = [0] * 1000
sleep(.1)
b = a * 100
sleep(.1)
c = b * 100
return a
mem_usage = memory_usage(f)
print('Memory usage (in chunks of .1 seconds): %s' % mem_usage)
print('Maximum memory usage: %s' % max(mem_usage))
</code></pre>
<p>在我的情况下(memory_profiler 0.25),如果打印以下输出:</p>
<pre><code>Memory usage (in chunks of .1 seconds): [45.65625, 45.734375, 46.41015625, 53.734375]
Maximum memory usage: 53.734375
</code></pre>