将 Float32Array 从工作线程发送到主线程的有效方法

问题描述 投票:0回答:1

我正在工作线程中运行推理运行时,它会生成 Float32 数组图像。 然后我需要使用 postMessage 将此数组发送到主线程。 在分析过程中我发现了很多奇怪的事情。

  1. 令人惊讶的是,worker 的推理速度慢了大约 3 倍(没有worker 时为 8 毫秒,有worker 时为 20 毫秒)。
  2. 在主线程中,onmessage 函数花费了大约 20ms 的时间。

没想到发送 512 x 256 float32 缓冲区会这么慢。

目前我正在尝试发送 ImageBitmap 而不是 Float32Array。但我没有找到从 float32array 创建 ImageBitmap 的方法。 ImageBitmap 支持浮点吗?

如果没有,我怎样才能有效地将数组数据从worker传输到main?

worker float32 imagebitmap
1个回答
1
投票

考虑使用 ArrayBuffer 或 SharedArrayBuffer 等可传输对象来直接转移内存的所有权,而不是复制数据。这避免了序列化/反序列化开销。

在工人中:

   postMessage(float32Array.buffer, [float32Array.buffer]); 
   // Transfer ownership of the buffer

在主线程中:

onmessage = function(event) {
const arrayBuffer = event.data;
const float32Array = new Float32Array(arrayBuffer);
// Use the float32Array
};

降低消息频率:

Batch multiple images into a single message instead of sending them individually.

Use a ring buffer or a similar data structure to manage the data transfer efficiently.

优化主线程处理:

Avoid heavy processing in the onmessage function.

Use requestAnimationFrame or setTimeout to schedule further processing and avoid blocking the main thread.

Offload processing to another worker if necessary.
© www.soinside.com 2019 - 2024. All rights reserved.