内存节省

目录

getsizeof()

tracemalloc 追踪内存

__slots__内存节省


1、查看内存占用

可以通过sys模块中的getsizeof()方法来查看占用。

from sys import getsizeof
class A():
    def __init__(self,a,b,c,d,e=0):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.e = e
p1 = A(1, 2, 3, 4)
print(getsizeof(p1.__dict__))
print(getsizeof(p1.a))
print(getsizeof(p1.b))
print(getsizeof(p1.c))
print(getsizeof(p1.d))
print(getsizeof(p1.e))
'''
68
14
14
14
14
12
44
'''

  创建了一个A类的一个实例,通过getsizeof()获取了所有动态绑定属性,可以发现:有默认值的参数,不传参,使用默认值,这时候这个属性所占用的字节数相比其他传参数的少。如果有默认值,也给他传递参数,则使用的字节数和普通的一样,这里省略代码。

2、dir()

dir() 可以查看对象中的所有方法

print(dir(object))
'''
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
'''

通过打印可以看到boject类中的大部分内置方法。

3、__slots__

  当一个类需要创建大量实例时,这样很消耗内存,可以通过__slots__声明实例所需要的属性,提高属性访问速度并减少内存消耗。

class A ( ):
    def __init__(self,a,b,c,d,e=0):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.e = e


class B ( ):
    __slots__ = ('a', 'b', 'c', 'd', 'e')
    def __init__(self,a,b,c,d,e=1):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.e = e
p1 = A(1, 2, 3, 4)
p2 = B(5, 6, 7,8,)
print(dir(p1))
print(dir(p2))
print(set(dir(p1))-set(dir(p2)))
print(set(dir(p2))-set(dir(p1)))
'''
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'c', 'd', 'e']
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', 'a', 'b', 'c', 'd', 'e']
{'__dict__', '__weakref__'}
{'__slots__'}
'''

通过以上代码和结果可以看出,使用__slots__的类中,没有__dict__、__weadref__,__dict__动态绑定属性是很消耗内存的,使用__slots__可以不调用这个方法,从而减少内存使用。

__weadref__ 弱引用,以后的博客会说到这个方法。

下面通过追踪内存,来看一下__slots__的用处。

首先是没有使用的:

import tracemalloc


class A ( ):
    def __init__(self,a,b,c,d,e=0):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.e = e


tracemalloc.start()
p1=[A(1, 2, 3, 4) for _ in range(100000)]
end=tracemalloc.take_snapshot()
internal = end.statistics('lineno')
for i in internal:
    print(i)
'''
F:/py/xx.py:117: size=6640 KiB, count=199992, average=34 B
F:/py/xx.py:135: size=3528 KiB, count=100001, average=36 B
F:/py/xx.py:136: size=348 B, count=1, average=348 B
D:\python\python3.7\lib\tracemalloc.py:532: size=36 B, count=1, average=36 B
'''

使用__slots__的:

import tracemalloc


class B ( ):
    __slots__ = ('a', 'b', 'c', 'd', 'e')
    def __init__(self,a,b,c,d,e=1):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.e = e


tracemalloc.start()
p2=[B(5, 6, 7, 8) for _ in range(100000)]
end=tracemalloc.take_snapshot()
internal = end.statistics('lineno')
for i in internal:
    print(i)
'''
F:/py/lanqiao.py:126: size=4699 KiB, count=100001, average=48 B
F:/py/lanqiao.py:127: size=348 B, count=1, average=348 B
D:\python\python3.7\lib\tracemalloc.py:532: size=36 B, count=1, average=36 B
'''

两个结过可以明显看出使用__slots__后,size总和少于不使用的。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值