Skip to content

Commit be2f8b2

Browse files
committed
Improve msgify(PointCloud2, array) performance by 100x
1 parent 238b6a2 commit be2f8b2

1 file changed

Lines changed: 11 additions & 1 deletion

File tree

ros2_numpy/point_cloud2.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939

4040
from .registry import converts_from_numpy, converts_to_numpy
4141

42+
import array
4243
import numpy as np
4344
from sensor_msgs.msg import PointCloud2, PointField
4445

@@ -165,7 +166,16 @@ def array_to_pointcloud2(cloud_arr, stamp=None, frame_id=None):
165166
cloud_msg.is_dense = \
166167
all([np.isfinite(
167168
cloud_arr[fname]).all() for fname in cloud_arr.dtype.names])
168-
cloud_msg.data = cloud_arr.tostring()
169+
170+
# The PointCloud2.data setter will create an array.array object for you if you don't
171+
# provide it one directly. This causes very slow performance because it iterates
172+
# over each byte in python.
173+
# Here we create an array.array object using a memoryview, limiting copying and
174+
# increasing performance.
175+
memory_view = memoryview(cloud_arr).cast("B")
176+
as_array = array.array("B")
177+
as_array.frombytes(memory_view)
178+
cloud_msg.data = as_array
169179
return cloud_msg
170180

171181
def merge_rgb_fields(cloud_arr):

0 commit comments

Comments
 (0)