From fffa3804aa66eb7cee2485fdf701cad52bfd31d7 Mon Sep 17 00:00:00 2001 From: Divy Srivastava Date: Wed, 8 Jan 2025 22:09:55 +0530 Subject: [PATCH] fix(ext/node): Fix `os.cpus()` on Linux (#27592) Populate `speed` using current scaling frequency and fix times multiplier. Fixes https://github.com/denoland/deno/issues/27555
Node.js Deno
``` > os.cpus() [ { model: 'AMD Ryzen 5 7530U with Radeon Graphics', speed: 1396, times: { user: 1769930, nice: 20, sys: 525630, idle: 41325700, irq: 110060 } }, ``` ``` > os.cpus() [ { model: "AMD Ryzen 5 7530U with Radeon Graphics", speed: 1630, times: [Object: null prototype] { user: 1795620, nice: 20, sys: 537840, idle: 41589390, irq: 111230 } }, ```
--- ext/node/ops/os/cpus.rs | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/ext/node/ops/os/cpus.rs b/ext/node/ops/os/cpus.rs index d9b28ce88c..4dd0e59a17 100644 --- a/ext/node/ops/os/cpus.rs +++ b/ext/node/ops/os/cpus.rs @@ -264,13 +264,16 @@ pub fn cpu_info() -> Option> { let nice = fields.next()?.parse::().ok()?; let sys = fields.next()?.parse::().ok()?; let idle = fields.next()?.parse::().ok()?; + let _iowait = fields.next()?.parse::().ok()?; let irq = fields.next()?.parse::().ok()?; - cpus[i].times.user = user; - cpus[i].times.nice = nice; - cpus[i].times.sys = sys; - cpus[i].times.idle = idle; - cpus[i].times.irq = irq; + // sysconf(_SC_CLK_TCK) is fixed at 100 Hz, therefore the + // multiplier is always 1000/100 = 10 + cpus[i].times.user = user * 10; + cpus[i].times.nice = nice * 10; + cpus[i].times.sys = sys * 10; + cpus[i].times.idle = idle * 10; + cpus[i].times.irq = irq * 10; } let fp = std::fs::File::open("/proc/cpuinfo").ok()?; @@ -287,6 +290,18 @@ pub fn cpu_info() -> Option> { let model = fields.next()?.trim(); cpus[j].model = model.to_string(); + + if let Ok(fp) = std::fs::File::open(format!( + "/sys/devices/system/cpu/cpu{}/cpufreq/scaling_cur_freq", + j + )) { + let mut reader = std::io::BufReader::new(fp); + let mut speed = String::new(); + reader.read_line(&mut speed).ok()?; + + cpus[j].speed = speed.trim().parse::().ok()? / 1000; + } + j += 1; }