Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python. get size of an object

Tags:

I need to know size of objects in my python program. I have for loop in which I need to know size of objects. If I use sys.getsizeof then memory does not free instantly and I cannot see actual size. Is there way to do it?

My objects are json and string. In the worst case I can save them to file and look at file sizes. But how can I look at file size from python code?

Edit: size of serialised objects is more important for me. so second part of the question is essential.

Thanks.

like image 441
ashim Avatar asked Apr 30 '12 16:04

ashim


People also ask

How do I get the size of a Python object?

In python, the usage of sys. getsizeof() can be done to find the storage size of a particular object that occupies some space in the memory. This function returns the size of the object in bytes.

What does __ sizeof __ do in Python?

Now let's look at the __sizeof__() method. It returns the size of the object without any overhead.

How do you determine the size of an object?

One way to get an estimate of an object's size in Java is to use getObjectSize(Object) method of the Instrumentation interface introduced in Java 5. As we could see in Javadoc documentation, the method provides “implementation-specific approximation” of the specified object's size.

How do you calculate byte size in Python?

Use the len() function to get the length of a bytes object, e.g. len(my_bytes) . The len() function returns the length (the number of items) of an object and can be passed a sequence (a bytes, string, list, tuple or range) or a collection (a dictionary, set, or frozen set).


1 Answers

Considering that type(json.dumps(something))==str you should be able to literally just use len.

Consider the following

obj = {'content' : 'something goes here'}
json_obj = json.dumps(obj)
json_size = len(json_obj)

serialized_size = len(serialized_object)

if json_size < serialized_size:
  print "I'd use the JSON with this..."
like image 169
lukecampbell Avatar answered Oct 07 '22 01:10

lukecampbell