Created
November 24, 2019 00:31
-
-
Save addaleax/248f9a012284353a578e6f2ef638b777 to your computer and use it in GitHub Desktop.
Buffer pool usage tracker
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
'use strict'; | |
const orig = Buffer.allocUnsafe; | |
const stats = { | |
inUse: 0, | |
allocated: 0 | |
}; | |
const group = new FinalizationGroup((holdings) => { | |
for (const info of holdings) { | |
if (info.type === 'Buffer') { | |
stats.inUse -= info.length; | |
} else { | |
stats.allocated -= info.length; | |
} | |
} | |
log(); | |
}); | |
const kSeen = Symbol('kSeen'); | |
Buffer.allocUnsafe = (...args) => { | |
const ret = orig(...args); | |
if (ret.buffer.byteLength === ret.length) return ret; | |
if (!ret.buffer[kSeen]) { | |
ret.buffer[kSeen] = true; | |
const info = { | |
type: 'ArrayBuffer', | |
length: ret.buffer.byteLength | |
}; | |
stats.allocated += ret.buffer.byteLength; | |
group.register(ret.buffer, info); | |
} | |
{ | |
const info = { | |
type: 'Buffer', | |
length: ret.length | |
}; | |
stats.inUse += ret.length; | |
group.register(ret, info); | |
} | |
log(); | |
return ret; | |
} | |
const allocationLog = []; | |
function log() { | |
allocationLog.push({ ts: process.hrtime.bigint(), ...stats }); | |
} | |
log(); | |
function getUsageRatio() { | |
log(); | |
const integratedStats = { | |
inUse: 0, | |
allocated: 0 | |
}; | |
for (let i = 0; i < allocationLog.length - 1; i++) { | |
const dur = Number(allocationLog[i + 1].ts - allocationLog[i].ts); | |
integratedStats.inUse += allocationLog[i].inUse * dur; | |
integratedStats.allocated += allocationLog[i].allocated * dur; | |
} | |
return integratedStats.inUse / integratedStats.allocated; | |
} | |
process.on('exit', () => { | |
console.log('Usage ratio: ', getUsageRatio().toFixed(5)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment