Python引用计数机制

原因:
1.Python 程序在运行时,需要在内存中开辟出一块空间,用于存放运行时产生的临时变量,计算完成后,再将结果输出到永久性存储器中。
2.但是当数据量过大,或者内存空间管理不善,就很容易出现内存溢出的情况,程序可能会被操作系统终止。

3.而对于服务器这种用于永不中断的系统来说,内存管理就显得更为重要了,不然很容易引发内存泄漏。
4.这里的内存泄漏是指程序本身没有设计好,导致程序未能释放已不再使用的内存,或者直接失去了对某段内存的控制,造成了内存的浪费。

1.函数外

# coding=utf-8
import os
import psutil
import gc, sys


# 显示当前 python 程序占用的内存大小
def show_memory_info(hint):
    pid = os.getpid( )
    p = psutil.Process(pid)

    info = p.memory_full_info( )
    memory = info.uss / 1024. / 1024
    print('{} memory used: {} MB'.format(hint, memory))


def func( ):
    global a  # 1
    show_memory_info('before')
    a = [i for i in range(10000000)]
    show_memory_info('after')
    # return a  # 2


func( )  # 1
# a = func( )  # 2
print("a引用次数:", sys.getrefcount(a))
del a  # 计数为零
gc.collect( )  # 启动垃圾回收
show_memory_info('finished')


输出:

before memory used: 8.5234375 MB
after memory used: 396.484375 MB
a引用次数: 2
finished memory used: 9.3203125 MB

2.函数内–循环引用

# coding=utf-8
import os
import psutil
import gc, sys


# 显示当前 python 程序占用的内存大小
def show_memory_info(hint):
    pid = os.getpid( )
    p = psutil.Process(pid)

    info = p.memory_full_info( )
    memory = info.uss / 1024. / 1024
    print('{} memory used: {} MB'.format(hint, memory))


def func( ):
    show_memory_info('initial')
    a = [i for i in range(10000000)]
    b = [i for i in range(10000000)]
    a.append(b)
    b.append(a)  # 引用了一次
    print("a引用次数:", sys.getrefcount(a))
    show_memory_info('after a, b created')


func( )
gc.collect( )  # 启动垃圾回收
show_memory_info('finished')

输出:

initial memory used: 8.59375 MB
a引用次数: 3
after a, b created memory used: 783.96484375 MB
finished memory used: 9.48828125 MB
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值