Last active
October 14, 2023 15:19
-
-
Save maksimr/fd57a87cae050c03cb36631f74945188 to your computer and use it in GitHub Desktop.
node profiler
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
import inspector from 'inspector'; | |
import { writeFile } from 'fs/promises'; | |
import cron from 'node-cron'; | |
class Profiler { | |
private session: inspector.Session; | |
constructor() { | |
this.session = new inspector.Session(); | |
} | |
public async connect() { | |
this.session.connect(); | |
} | |
public async startCpuProfiling() { | |
await this.sessionPost('Profiler.enable'); | |
await this.sessionPost('Profiler.start'); | |
} | |
public async stopCpuProfiling() { | |
const { profile } = await this.sessionPost<inspector.Profiler.StopReturnType>('Profiler.stop'); | |
await this.sessionPost('Profiler.disable'); | |
return profile; | |
} | |
public async disconnect() { | |
this.session.disconnect(); | |
} | |
private async sessionPost<T>(method: string, params?: any): Promise<T> { | |
return new Promise((resolve, reject) => { | |
this.session.post(method, params, (error, result) => { | |
if (error) reject(error); | |
else resolve(result as T); | |
}); | |
}); | |
} | |
} | |
async function main() { | |
cron.schedule('*/10 * * * * *', async () => { | |
const profiler = new Profiler(); | |
await profiler.connect(); | |
await profiler.startCpuProfiling(); | |
await new Promise(resolve => setTimeout(resolve, 5000)); | |
const profile = await profiler.stopCpuProfiling(); | |
await profiler.disconnect(); | |
await writeFile('profile.cpuprofile', JSON.stringify(profile)); | |
}); | |
setInterval(function doWork() { | |
const date = Date.now(); | |
const delay = Math.floor(Math.random() * 200); | |
while (Date.now() < date + delay) { | |
// do nothing | |
} | |
}, 100); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment