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.
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.
Now let's look at the __sizeof__() method. It returns the size of the object without any overhead.
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.
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).
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..."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With