[英]Fastest way to convert a bytearray into a numpy array
I have a bytearray
which I want to convert to a numpy array of int16
to perform FFT operations on.我有一个字节数组,我想将其转换为
bytearray
的int16
数组以执行 FFT 操作。 The bytearray is coming out of a UDP socket so first I convert two consecutive bytes into an int16
using struct.unpack
, and then convert it a numpy array using np.asarray
. bytearray 来自 UDP 套接字,所以首先我使用 struct.unpack 将两个连续字节转换为
int16
,然后使用struct.unpack
将其转换为np.asarray
数组。
Current approach, however, is too slow.然而,目前的方法太慢了。 Original
bytearray
is of length 1e6 bytes, so each of the mentioned steps ( struct.unpack
and np.asarray
) takes 20 ms and with a total of 40ms.原始
bytearray
的长度为 1e6 字节,因此上述每个步骤( struct.unpack
和np.asarray
)需要 20 毫秒,总共需要 40 毫秒。 This is a relatively long frame time for my applications so I need it a bit shortened.对于我的应用程序来说,这是一个相对较长的帧时间,所以我需要缩短一点。
Currently, I'm doing this:目前,我正在这样做:
temp1 = self.data_buffer[0:FRAME_LEN_B]
self.temp_list = np.asarray(struct.unpack('h' * (len(temp1) // 2), temp1))
You can try np.frombuffer
.你可以试试
np.frombuffer
。 This can wrap any object supporting the buffer protocol , whichbytearray
explicitly does, into an array:这可以将任何支持缓冲区协议的 object (
bytearray
明确执行)包装到一个数组中:
arr = np.frombuffer(self.data_buffer, dtype=np.int16, size=FRAME_LEN_B // 2)
You can manipulate the array however you want after that: slice, reshape, transpose, etc.之后,您可以随心所欲地操作数组:切片、整形、转置等。
If your native byte order is opposite to what you have coming in from the network, you can swap the interpretation order without having to swap the data in-place:如果您的本机字节顺序与您从网络传入的字节顺序相反,您可以交换解释顺序而无需就地交换数据:
dt = np.dtype(np.int16)
dt.newbyteorder('>')
arr = np.frombuffer(self.data_buffer, dtype=dt, size=FRAME_LEN_B // 2)
If the order is non-native, operations on the array may take longer, as the data will have to be swapped every time on the fly.如果订单是非本地的,则对数组的操作可能需要更长的时间,因为每次都必须即时交换数据。 You can therefore change the byte order in-place ahead of time if that is the case:
因此,如果是这种情况,您可以提前就地更改字节顺序:
arr.byteswap(inplace=True)
This will overwrite the contents of the original packet.这将覆盖原始数据包的内容。 If you want to make a separate copy, just set
inplace=False
, which is the default.如果要制作单独的副本,只需设置
inplace=False
,这是默认设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.