python吃内存吗_如何使用Python吃掉内存?

您将无法使用诸如s = ' ' * BIG_NUMBER

最好附加一个列表,如a = []

while True:

print len(a)

a.append(' ' * 10**6)

下面是一个较长的代码,它可以更深入地了解内存分配限制:import os

import psutil

PROCESS = psutil.Process(os.getpid())

MEGA = 10 ** 6

MEGA_STR = ' ' * MEGA

def pmem():

tot, avail, percent, used, free = psutil.virtual_memory()

tot, avail, used, free = tot / MEGA, avail / MEGA, used / MEGA, free / MEGA

proc = PROCESS.get_memory_info()[1] / MEGA

print('process = %s total = %s avail = %s used = %s free = %s percent = %s'

% (proc, tot, avail, used, free, percent))

def alloc_max_array():

i = 0

ar = []

while True:

try:

#ar.append(MEGA_STR) # no copy if reusing the same string!

ar.append(MEGA_STR + str(i))

except MemoryError:

break

i += 1

max_i = i - 1

print 'maximum array allocation:', max_i

pmem()

def alloc_max_str():

i = 0

while True:

try:

a = ' ' * (i * 10 * MEGA)

del a

except MemoryError:

break

i += 1

max_i = i - 1

_ = ' ' * (max_i * 10 * MEGA)

print 'maximum string allocation', max_i

pmem()

pmem()

alloc_max_str()

alloc_max_array()

这是我得到的输出:process = 4 total = 3179 avail = 2051 used = 1127 free = 2051 percent = 35.5

maximum string allocation 102

process = 1025 total = 3179 avail = 1028 used = 2150 free = 1028 percent = 67.7

maximum array allocation: 2004

process = 2018 total = 3179 avail = 34 used = 3144 free = 34 percent = 98.9

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python程序的内存使用情况可以使用Python内置的`memory_profiler`模块进行监视。`memory_profiler`可以帮助我们分析Python程序的内存使用情况,找出内存泄漏等问题。 安装`memory_profiler`模块: ```python pip install memory_profiler ``` 使用`memory_profiler`监视Python程序的内存使用情况: 1. 在需要监视的函数上添加`@profile`装饰器。 2. 运行程序时加上`-m memory_profiler`参数,并指定要监视的文件名。 例如,我们有以下Python程序: ```python from random import randint @profile def generate_list(): nums = [randint(0, 100) for _ in range(1000000)] return nums if __name__ == '__main__': nums = generate_list() print(sum(nums)) ``` 我们可以在`generate_list()`函数上加上`@profile`装饰器,然后运行以下命令: ```python python -m memory_profiler memory_test.py ``` 输出结果: ``` Filename: memory_test.py Line # Mem usage Increment Line Contents ================================================ 3 52.5 MiB 52.5 MiB @profile 4 def generate_list(): 5 81.9 MiB 29.4 MiB nums = [randint(0, 100) for _ in range(1000000)] 6 81.9 MiB 0.0 MiB return nums 12671490 ``` 输出结果中,`Line #`表示代码行号,`Mem usage`表示该行执行后的内存使用情况,`Increment`表示相对于上一行的内存增加量,`Line Contents`表示该行代码内容。我们可以看到,在`generate_list()`函数中,内存使用量从52.5 MiB增加到81.9 MiB,增加了29.4 MiB,随着程序的执行结束,内存使用量又降回到了52.5 MiB。 通过`memory_profiler`模块的输出结果,我们可以找出Python程序中的内存泄漏和不必要的内存占用,从而进行优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值