Monday, July 11, 2022

[FIXED] How to get ROS MSG length in python?

Issue

I have a problem that needs to count the length of each ROS topic msg.

I modified rostopic(/opt/ros/smart-ros/lib/python2.7/dist-packages/rostopic / __ init__.py):

Class CallbackEcho(object) ->
Def callback (self, data, callback_args, current_time = None):
    Print('message length =',sys.getsizeof(data)) #statics msg length

But when the message contains a vector or struct list, the length is incorrect.

Please help solve this problem?

Thanks.


Solution

The problem is the behaviour of sys.getsizeof:

Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.

This means only the size of the reference to a list is used to calculate the object size.

There are already a few questions dealing with this:

The solution is to use Pympler and its module asizeof which provides a function to the required calculation:

Function asizeof calculates the combined (approximate) size of one or several Python objects in bytes

After installing the package using pip

pip install pympler

and importing it to your code like

from pympler.asizeof import asizeof

you are able to print the correct object size in your callback like

print('Size: ' + str(asizeof(data)))


Answered By - Fruchtzwerg
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.