简体   繁体   中英

Measure the use of CPU of a Nodejs process from within the same Nodejs process

I would like to measure the CPU consumed by a main nodejs process, ie a single process which does not have any child process, from within that same process.

From the documentation it seems that process.cpuUsage is the guy I am looking for. There is something though that I do not fully grasp.

From the official documentation

The process.cpuUsage() method returns the user and system CPU time usage of the current process, in an object with properties user and system, whose values are microsecond values (millionth of a second). These values measure time spent in user and system code respectively, and may end up being greater than actual elapsed time if multiple CPU cores are performing work for this process .

What I do not understand is the last sentence. If a node process is single threaded how can it be that multiple CPU cores perform work for this process ?

What I do not understand is the last sentence. If a node process is single threaded how can it be that multiple CPU cores perform work for this process?

Nodejs runs your Javascript as a single thread (unless you specifically use Worker Threads), but the node.js library itself uses a number of native threads. For example, the file I/O part of libuv uses a thread pool for disk I/O and multiple threads can be involved in running the native code part of the fs module. In addition, some add-on modules that have native code may use their own native code threads to help them accomplish their goal.

So, in a running node.js program, there may be multiple CPUs contributing to the overall code of the process depending upon exactly what it's doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM