From 7f75d988c262bd3a8f0a32ce249e9502135823e7 Mon Sep 17 00:00:00 2001 From: srgooglo Date: Fri, 13 May 2022 14:46:43 +0200 Subject: [PATCH] added `cpu` lib --- .../streaming-server/src/lib/cpu/index.js | 45 +++++++++++++++++++ packages/streaming-server/src/lib/index.js | 3 +- 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 packages/streaming-server/src/lib/cpu/index.js diff --git a/packages/streaming-server/src/lib/cpu/index.js b/packages/streaming-server/src/lib/cpu/index.js new file mode 100644 index 00000000..1d9b9ad0 --- /dev/null +++ b/packages/streaming-server/src/lib/cpu/index.js @@ -0,0 +1,45 @@ +import os from "os" + +export function averageUsage() { + //Initialise sum of idle and time of cores and fetch CPU info + let totalIdle = 0, totalTick = 0 + let cpus = os.cpus() + + //Loop through CPU cores + for (let i = 0, len = cpus.length; i < len; i++) { + //Select CPU core + let cpu = cpus[i] + + //Total up the time in the cores tick + if (cpu.times.type) { + for (type in cpu.times) { + totalTick += cpu.times[type] + } + } + + //Total up the idle time of the core + totalIdle += cpu.times.idle + } + + //Return the average Idle and Tick times + return { idle: totalIdle / cpus.length, total: totalTick / cpus.length } +} + +export function percentageUsage() { + return new Promise((resolve, reject) => { + let startMeasure = averageUsage() + + setTimeout(() => { + let endMeasure = averageUsage() + + //Calculate the difference in idle and total time between the measures + let idleDifference = endMeasure.idle - startMeasure.idle + let totalDifference = endMeasure.total - startMeasure.total + + //Calculate the average percentage CPU usage + let percentageCPU = 100 - ~~(100 * idleDifference / totalDifference) + + return resolve(percentageCPU) + }, 100) + }) +} \ No newline at end of file diff --git a/packages/streaming-server/src/lib/index.js b/packages/streaming-server/src/lib/index.js index a74fde00..6c99fae7 100644 --- a/packages/streaming-server/src/lib/index.js +++ b/packages/streaming-server/src/lib/index.js @@ -1 +1,2 @@ -export { default as getStreamingKeyFromStreamPath } from "./getStreamingKeyFromStreamPath" \ No newline at end of file +export { default as getStreamingKeyFromStreamPath } from "./getStreamingKeyFromStreamPath" +export * as cpu from "./cpu" \ No newline at end of file