get system cpu frequency in typescript

You can obtain the CPU frequency of your system in Node.js using the os module.

Here's the code snippet to get the CPU frequency in Hz:

index.ts
import os from 'os';

const cpuFreq = os.cpus()[0].speed; // in Hz
console.log(cpuFreq); // logs the CPU frequency in Hz (e.g. 2900000000)
139 chars
5 lines

If you want to convert the frequency to GHz, you can simply divide the frequency by 1_000_000_000:

index.ts
const cpuFreqGHz = cpuFreq / 1_000_000_000;
console.log(cpuFreqGHz.toString() + ' GHz'); // logs the CPU frequency in GHz (e.g. 2.9 GHz)
137 chars
3 lines

Note that the os.cpus() method returns an array of objects containing information about each CPU/core in the system. In this example, I'm assuming that you only have one CPU/core, and getting the frequency of the first (0th index) element. If you want to get the frequency of all CPUs/cores, you can simply iterate through the array returned by os.cpus().

gistlibby LogSnag