Skip to content

Thread pool vs synchronous performance example (for your information) #40

@qpwo

Description

@qpwo

Hope this is of some use to you! The threads broke even at 10000000 and beyond that did much better than synchronous

// random-number-sum-performance-test.js
const { performance } = require('perf_hooks')

const { StaticPool } = require('node-worker-threads-pool')

let n = 1
async function main() {
    n = 1
    for (let exponent = 0; exponent < 9; exponent++) {
        n *= 10
        console.log(`--- n=${n}: ---`)
        await time(withPool)
        await time(nothingFancy)
    }
}
main()

async function withPool() {
    const staticPool = new StaticPool({
        size: 4,
        task: n => {
            let total = 0
            for (let i = 0; i < n; i++) total += Math.random()
            return total
        },
    })

    const total = (await Promise.all([1, 2, 3, 4].map(() => staticPool.exec(n)))).reduce((a, b) => a + b)
    return total
}

function nothingFancy() {
    let total = 0
    const m = n * 4
    for (let i = 0; i < m; i++) total += Math.random()
    return total
}

async function time(f) {
    const t1 = performance.now()
    const result = await f()
    const t2 = performance.now()
    console.log(`${f.name} took ${t2 - t1} to get ${result}`)
}

Results:

--- n=10: ---
withPool took 53.835896998643875 to get 19.930073961113138
nothingFancy took 0.06096699833869934 to get 16.237419498424664
--- n=100: ---
withPool took 53.99462300539017 to get 191.49533349250487
nothingFancy took 0.027156993746757507 to get 204.45374014731104
--- n=1000: ---
withPool took 50.01943700015545 to get 2004.4566054103996
nothingFancy took 0.9318670034408569 to get 2015.9208923115145
--- n=10000: ---
withPool took 48.72436600923538 to get 20007.1920261762
nothingFancy took 2.4409569948911667 to get 20012.901073635243
--- n=100000: ---
withPool took 54.470831006765366 to get 200086.70983438176
nothingFancy took 5.684918999671936 to get 199998.26497395104
--- n=1000000: ---
withPool took 66.65430599451065 to get 2001061.973088672
nothingFancy took 43.69860699772835 to get 1999745.198802261
--- n=10000000: ---
withPool took 172.60957700014114 to get 19998626.755245283
nothingFancy took 377.86564199626446 to get 20002634.54283542
--- n=100000000: ---
withPool took 1268.5459830015898 to get 199999921.15196624
nothingFancy took 4249.29148799181 to get 200004158.20174262
--- n=1000000000: ---
withPool took 12684.676231995225 to get 1999962044.2081757
nothingFancy took 49840.80099800229 to get 1999954981.8320045

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions