简体   繁体   中英

CPU usage as a percentage for the whole system?

I'm trying to make a botinfo command with resource usage stats. I've got memory covered (although percentage for memory usage would be nice too) but I can't seem to get cpu usage. I've tried multiple packages and methods, none worked. My memory thing is:

const usedMemory = os.totalmem() - os.freemem()

How would I make cpu usage and return it in an discord.js embed?

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.

The result of a previous call to process.cpuUsage() can be passed as the argument to the function, to get a diff reading.

import { cpuUsage } from 'process';

const startUsage = cpuUsage();
// { user: 38579, system: 6986 }

// spin the CPU for 500 milliseconds
const now = Date.now();
while (Date.now() - now < 500);

console.log(cpuUsage(startUsage));
// { user: 514883, system: 11226 }

For more details check here .

If you want to get in %, you can use existing npm module: node-os-utils . You can use it like this:

const osu = require('node-os-utils')
const cpu = osu.cpu

const count = cpu.count() // 8

cpu.usage()
  .then(cpuPercentage => {
    console.log(cpuPercentage) // 10.38
  })

const osCmd = osu.osCmd

osCmd.whoami()
  .then(userName => {
    console.log(userName) // admin
  })

For more details, check the documentation here .

I found a way to do it. There's a function in node-os-utils ( https://www.npmjs.com/package/node-os-utils ) called loadavgTime that needs to be used with loadavg-windows ( https://www.npmjs.com/package/loadavg-windows ) if you're on windows. It takes the os.loadavg from the last minute by default. I then divided it by 2 and then multiplied by 10 cos for some reason it outputs a weird number (between 1.__ and 2.__). It gives it as a percentage, you just need to add the % after it when console.log ing it. Here's the code:

const osu = require('node-os-utils')
require('loadavg-windows')

const cpu = osu.cpu
const usage = (cpu.loadavgTime() / 2) * 10

console.log(usage)

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