Is there any way to find out sizeof an object

3 views
Skip to first unread message

srinivasan srinivas

unread,
Jun 24, 2008, 1:00:38 AM6/24/08
to pytho...@python.org
Hi,
I have written a class which has some attributes. I want to know how do i find out the size of an instance of this class??
class T(object):
    def __init__(self, fn_name, *args, **kwds):
        self.fn_name = fn_name
        self.args = args
        self.kwds = kwds
Thanks,
Srini


Bollywood, fun, friendship, sports and more. You name it, we have it on http://in.promos.yahoo.com/groups/bestofyahoo/

"Martin v. Löwis"

unread,
Jun 24, 2008, 2:34:02 AM6/24/08
to
> I have written a class which has some attributes. I want to know how
> do i find out the size of an instance of this class??
> class T(object):
> def __init__(self, fn_name, *args, **kwds):
> self.fn_name = fn_name
> self.args = args
> self.kwds = kwds

In Python 2.6, you can use sys.getsizeof to find out how large an object
is. Notice that this is a really tricky question: Assuming you have

t = T(1,2,3, a="hello", b="world")

then you should certainly consider the size atleast

sys.getsizeof(t) + sys.getsizeof(t.__dict__)

But then you also have the attribute values (i.e. the tuple resp.
dict), which you might want to account for:

+ sys.getsizeof(t.args) + sys.getsizeof(t.dict)

Now, what to do about the sizes of the various items in the dict
and the tuple? One could do

total = ... # from above
for o in t.args:
total+=sys.getsizeof(o)
for k,v in t.kwds.items():
total+=sys.getsizeof(k)+sys.getsizeof(v)

However, that might be accounting too much, since the at least
the keys of the dict are shared across other dicts. Likewise,
the integers are shared, and the string literals (as written
above) would be shared if the very same T constructor is run
twice.

In short, "size of an instance" can't be answered without
a specific instance (i.e. you can't answer it in advance for
all instances), plus even for a single instance, its difficult
to answer.

Regards,
Martin

Paddy

unread,
Jun 24, 2008, 3:44:47 AM6/24/08
to
On Jun 24, 6:00 am, srinivasan srinivas <sri_anna...@yahoo.co.in>
wrote:

Check memory
Create a million
Check memory
Do maths!

;-)

- Paddy.

zooko

unread,
Jun 26, 2008, 12:56:00 PM6/26/08
to
Here are a few little tools that I developed to do this kind of thing:

http://allmydata.org/trac/pyutil/browser/pyutil/pyutil/memutil.py

Regards,

Zooko

Reply all
Reply to author
Forward
0 new messages