Given an arbitrary async function in Node.js, is there any way to properly measure the CPU usage of that function, including all of its async microtasks?
I thought async_hooks
was the way to do this, but I’m not sure how and it’s now marked as deprecated. The deprecation notice links to AsyncLocalStorage
for context tracking (which we use already) and this new diagnostics_channel
API, which seems unhelpful and irrelevant to this (although the documentation for that is so unclear that I could be wrong).
Note that this is for continuous monitoring of a large system, so using the debugger is not relevant. At the moment we’ve just got the overall CPU usage of the process, but it would be more much helpful if we could break this down to get metrics for different parts of the system.
2
Answers
You could potentially run the functions in node child processes. And then find the process PID and then ask the system for information about that PID.
The process of getting information from the PID varies from system to system depending on the OS and bash commands available, however I was able to find this module to simplify the process.
You might consider using a Flame Graph for that. It would give you more context than watching a single async function.
https://nodejs.org/en/learn/diagnostics/flame-graphs