Created
August 10, 2024 04:36
-
-
Save sujaykumarh/5c1cf08efe44edf2d9f1614860827cf0 to your computer and use it in GitHub Desktop.
JS Parallel Processing using bun
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Refrence from https://stackoverflow.com/a/42114595 | |
// Tested on Bun v1.1.21 - https://bun.sh | |
// date: 10-08-2024 | |
// console.clear(); | |
// Testing | |
const TOTAL_TASKS = 5; | |
// const TOTAL_TASKS = 10; | |
// const TOTAL_TASKS = 100; | |
// const TOTAL_TASKS = 1000; | |
// const TOTAL_TASKS = 10000; | |
const TASK_DELAY = 500; // in ms | |
const wait: Function = (ms: number, data: any): any => { | |
return new Promise(resolve => setTimeout(resolve.bind(self, data), ms)); | |
} | |
/** | |
* These will be run in series, because we call | |
* a function and immediately wait for each result, | |
* so this will finish in (TOTAL_TASKS * TASK_DELAY). | |
*/ | |
async function series(): Promise<any> { | |
let results: Array<any> = []; | |
for (let idx = 1; idx <= TOTAL_TASKS; idx++) { | |
const taskResult = await wait(TASK_DELAY, `s-task_${idx}`); | |
results.push(taskResult); | |
} | |
return results; | |
} | |
/** | |
* While here we call the functions first, | |
* then wait for the result later, so | |
* this will finish in around TASK_DELAY ms. | |
*/ | |
async function parallel(): Promise<any> { | |
let tasks: Array<Function> = []; | |
for (let idx = 1; idx <= TOTAL_TASKS; idx++) { | |
tasks.push(wait(TASK_DELAY, `p-task_${idx}`)); | |
} | |
return await Promise.all(tasks); | |
} | |
async function taskRunner(fn: Function, label: string) { | |
const startTime = performance.now(); | |
console.log(`${TOTAL_TASKS} ${label} tasks starting...`); | |
let result = await fn(); | |
console.log(`${TOTAL_TASKS} ${label} tasks finished in ${(performance.now() - startTime)} ms with following result:`); | |
console.log(result); | |
console.log(""); | |
} | |
void taskRunner(series, 'series'); | |
void taskRunner(parallel, 'parallel'); | |
console.log(""); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment