Skip to content

Commit

Permalink
add a note about using __slots__
Browse files Browse the repository at this point in the history
  • Loading branch information
crazyguitar committed Jan 20, 2018
1 parent dcc23be commit 16b3fe2
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions docs/notes/python-basic.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1333,6 +1333,70 @@ Parsing csv string
['foo', 'bar', 'baz']
Using ``__slots__`` to save memory
-----------------------------------
.. code-block:: python
#!/usr/bin/env python3
import resource
import platform
import functools
def profile_mem(func):
@functools.wraps(func)
def wrapper(*a, **k):
s = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
ret = func(*a, **k)
e = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
uname = platform.system()
if uname == "Linux":
print(f"mem usage: {e - s} kByte")
elif uname == "Darwin":
print(f"mem usage: {e - s} Byte")
else:
raise Exception("not support")
return ret
return wrapper
class S(object):
__slots__ = ['attr1', 'attr2', 'attr3']
def __init__(self):
self.attr1 = "Foo"
self.attr2 = "Bar"
self.attr3 = "Baz"
class D(object):
def __init__(self):
self.attr1 = "Foo"
self.attr2 = "Bar"
self.attr3 = "Baz"
@profile_mem
def alloc(cls):
_ = [cls() for _ in range(1000000)]
alloc(S)
alloc(D)
output:
.. code-block:: console
$ python3.6 s.py
mem usage: 70922240 Byte
mem usage: 100659200 Byte
Using annotation to check type
-------------------------------
Expand Down

0 comments on commit 16b3fe2

Please sign in to comment.