简体   繁体   English

从同一个 Nodejs 进程中测量 Nodejs 进程的 CPU 使用率

[英]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.我想从同一个进程中测量一个主nodejs进程消耗的CPU,即一个没有任何子进程的单个进程。

From the documentation it seems that process.cpuUsage is the guy I am looking for.从文档看来process.cpuUsage是我要找的人。 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). process.cpuUsage() 方法返回当前进程的用户和系统 CPU 时间使用情况,在 object 中,具有 user 和 system 属性,其值为微秒值(百万分之一秒)。 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 .这些值分别衡量用户和系统代码所花费的时间,如果多个 CPU 内核正在为此进程执行工作,最终可能会大于实际经过的时间

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 ?如果节点进程是单线程的,那么多个 CPU 内核如何为该进程执行工作

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?如果节点进程是单线程的,那么多个 CPU 内核如何为该进程执行工作?

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. Nodejs 将 Javascript 作为单线程运行(除非您专门使用工作线程),但 node.js 库本身使用许多本机线程。 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.例如,libuv 的文件 I/O 部分使用线程池进行磁盘 I/O,并且可以涉及多个线程来运行fs模块的本机代码部分。 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.因此,在一个正在运行的 node.js 程序中,可能有多个 CPU 对进程的整体代码做出贡献,具体取决于它在做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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