我正在工作线程中运行推理运行时,它会生成 Float32 数组图像。 然后我需要使用 postMessage 将此数组发送到主线程。 在分析过程中我发现了很多奇怪的事情。
没想到发送 512 x 256 float32 缓冲区会这么慢。
目前我正在尝试发送 ImageBitmap 而不是 Float32Array。但我没有找到从 float32array 创建 ImageBitmap 的方法。 ImageBitmap 支持浮点吗?
如果没有,我怎样才能有效地将数组数据从worker传输到main?
考虑使用 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.