aboutsummaryrefslogtreecommitdiff
path: root/src/tasks/cpuUsage.ts
diff options
context:
space:
mode:
authorIRONM00N <64110067+IRONM00N@users.noreply.github.com>2022-07-07 20:22:54 +0200
committerIRONM00N <64110067+IRONM00N@users.noreply.github.com>2022-07-07 20:22:54 +0200
commit3b229fecbd71ac98bf17bb7a41bcb53cbbc5510c (patch)
treee04b23e782c50f3349b4654337e8292a9fa82774 /src/tasks/cpuUsage.ts
parent4f32de01e073820e4549618b5727a662a90bc7bf (diff)
downloadtanzanite-3b229fecbd71ac98bf17bb7a41bcb53cbbc5510c.tar.gz
tanzanite-3b229fecbd71ac98bf17bb7a41bcb53cbbc5510c.tar.bz2
tanzanite-3b229fecbd71ac98bf17bb7a41bcb53cbbc5510c.zip
extract needed part of node-os-utils and uninstall it
Diffstat (limited to 'src/tasks/cpuUsage.ts')
-rw-r--r--src/tasks/cpuUsage.ts50
1 files changed, 48 insertions, 2 deletions
diff --git a/src/tasks/cpuUsage.ts b/src/tasks/cpuUsage.ts
index f456c31..61e7a54 100644
--- a/src/tasks/cpuUsage.ts
+++ b/src/tasks/cpuUsage.ts
@@ -1,5 +1,5 @@
import { BushTask, Time } from '#lib';
-import osu from 'node-os-utils';
+import os from 'node:os';
export default class CpuUsageTask extends BushTask {
public constructor() {
@@ -10,7 +10,53 @@ export default class CpuUsageTask extends BushTask {
}
public async exec() {
- const cpuStats = await osu.cpu.usage(this.client.stats.cpu === undefined ? 100 * Time.Millisecond : Time.Minute);
+ const cpuStats = await cpu.usage(this.client.stats.cpu === undefined ? 100 * Time.Millisecond : Time.Minute);
this.client.stats.cpu = cpuStats;
}
}
+
+/* Everything inside the cpu namespace is adapted from the "node-os-utils" npm package which is licensed under a MIT license by Sunil Wang */
+namespace cpu {
+ export function usage(interval = Time.Second): Promise<number> {
+ return new Promise((resolve) => {
+ const startMeasure = average();
+
+ setTimeout(() => {
+ const endMeasure = average();
+ const idleDifference = endMeasure.avgIdle - startMeasure.avgIdle;
+ const totalDifference = endMeasure.avgTotal - startMeasure.avgTotal;
+ const cpuPercentage = (10000 - Math.round((10000 * idleDifference) / totalDifference)) / 100;
+
+ return resolve(cpuPercentage);
+ }, interval);
+ });
+ }
+
+ export function average(): CpuAverageInfo {
+ let totalIdle = 0;
+ let totalTick = 0;
+ const cpus = os.cpus();
+
+ for (let i = 0, len = cpus.length; i < len; i++) {
+ const cpu = cpus[i];
+ for (const type in cpu.times) {
+ totalTick += cpu.times[type as keyof typeof cpu.times];
+ }
+ totalIdle += cpu.times.idle;
+ }
+
+ return {
+ totalIdle: totalIdle,
+ totalTick: totalTick,
+ avgIdle: totalIdle / cpus.length,
+ avgTotal: totalTick / cpus.length
+ };
+ }
+
+ export interface CpuAverageInfo {
+ totalIdle: number;
+ totalTick: number;
+ avgIdle: number;
+ avgTotal: number;
+ }
+}