Files
performance-tests/wasm_pthread_worker.js

116 lines
2.2 KiB
JavaScript
Raw Normal View History

2025-11-18 12:55:09 +01:00
import { Worker } from 'worker_threads';
import { isMainThread } from 'worker_threads';
import { parentPort } from 'worker_threads';
import { workerData } from 'worker_threads';
import { URL } from 'node:url';
import fs from 'fs/promises';
import { setupWebAssembly } from "./shared_pthread.js"
const wasmBuffer = await fs.readFile('./binaries/wasm_add_pthread.wasm');
const __filename = new URL('', import.meta.url).pathname;
const __dirname = new URL('.', import.meta.url).pathname;
const NUM_THREADS = 12;
const ARRAY_SIZE = 15000576;
function getTime() {
const ns = process.hrtime.bigint();
return Number( ns ) / 1e9; // Returns seconds
}
if( isMainThread ) {
console.log("isMainThread");
let start;
var end;
start = getTime();
const sharedArrayBufferA = new SharedArrayBuffer(ARRAY_SIZE * 4);
const sharedArrayBufferB = new SharedArrayBuffer(ARRAY_SIZE * 4);
const sharedArrayBufferC = new SharedArrayBuffer(ARRAY_SIZE * 4);
const a = new Float32Array(sharedArrayBufferA);
const b = new Float32Array(sharedArrayBufferB);
const c = new Float32Array(sharedArrayBufferC);
end = getTime();
const allocTime = end - start;
// Time array initialization (single-threaded, like original C)
start = getTime();
for (let i = 0; i < ARRAY_SIZE; i++) {
a[i] = i;
b[i] = i * 2;
}
end = getTime();
const initTime = end - start;
const chunkSize = Math.floor(ARRAY_SIZE / NUM_THREADS)
const workerPromises = new Array();
for (let t = 0; t < NUM_THREADS; t++) {
const workerStart = t * chunkSize;
const workerEnd = (t === NUM_THREADS - 1) ? ARRAY_SIZE : (t + 1) * chunkSize;
const workerData = {
start: workerStart,
end: workerEnd,
sharedArrayBufferA,
sharedArrayBufferB,
sharedArrayBufferC
};
const worker = new Worker( __filename, { workerData: workerData });
workerPromises.push(new Promise((resolve, reject) => {
worker.on('exit', resolve);
worker.on('error', reject);
}));
}
} else {
console.log("other Threads");
// here the ?
setupWebAssembly( wasmBuffer, workerData, ARRAY_SIZE, NUM_THREADS );
}