How to find out the % CPU usage for Node.js process?

前端 未结 6 1368
挽巷
挽巷 2021-01-31 18:59

Is there a way to find out the cpu usage in % for a node.js process via code. So that when the node.js application is running on the server and detects the CPU exceeds certain %

6条回答
  •  执念已碎
    2021-01-31 19:40

    Use node process.cpuUsage function (introduced in node v6.1.0). It shows time that cpu spent on your node process. Example taken from docs:

    const previousUsage = process.cpuUsage();
    // { user: 38579, system: 6986 }
    
    // spin the CPU for 500 milliseconds
    const startDate = Date.now();
    while (Date.now() - startDate < 500);
    
    // At this moment you can expect result 100%
    // Time is *1000 because cpuUsage is in us (microseconds)
    const usage = process.cpuUsage(previousUsage);
    const result = 100 * (usage.user + usage.system) / ((Date.now() - startDate) * 1000) 
    console.log(result);
    
    // set 2 sec "non-busy" timeout
    setTimeout(function() {
        console.log(process.cpuUsage(previousUsage);
        // { user: 514883, system: 11226 }    ~ 0,5 sec
        // here you can expect result about 20% (0.5s busy of 2.5s total runtime, relative to previousUsage that is first value taken about 2.5s ago)
    }, 2000);
    

提交回复
热议问题