@@ -5,7 +5,9 @@ import { execCommand, sleep } from './utils';
55/** Intervall in milliseconds at which CPU utilization is computed. */
66export let CPU_COMPUTE_UTILIZATION_INTERVAL = 1000 ;
77
8- const PREV_CPU_CORES : os . CpuInfo [ ] = [ ] ;
8+ const CPU_COMPUTE_UTILIZATION_INITIAL_DELAY = 50 ;
9+
10+ let PREV_CPU_CORES : os . CpuInfo [ ] = [ ] ;
911let CPU_CORE_UTILIZATIONS : number [ ] = [ ] ;
1012let CPU_UTILIZATION : number = 0 ;
1113let CPU_COMPUTE_RUNNING = false ;
@@ -24,7 +26,7 @@ async function computeCpuUtilization() {
2426 const prev = PREV_CPU_CORES [ i ] as os . CpuInfo ;
2527 const next = cpuCores [ i ] as os . CpuInfo ;
2628
27- const nextUsage = next . times . user + next . times . nice + next . times . sys + next . times . irq ;
29+ const nextUsage = ( next . times . user + next . times . nice + next . times . sys + next . times . irq ) * 1.0 ;
2830 const prevUsage = prev . times . user + prev . times . nice + prev . times . sys + prev . times . irq ;
2931 const usage = nextUsage - prevUsage ;
3032
@@ -37,12 +39,14 @@ async function computeCpuUtilization() {
3739 totalTotal += total ;
3840 }
3941 CPU_UTILIZATION = totalTotal !== 0 ? totalUsage / totalTotal : 0 ;
42+ PREV_CPU_CORES = cpuCores ;
4043}
4144
4245async function runCpuComputeInterval ( ) {
4346 CPU_COMPUTE_RUNNING = true ;
4447 await computeCpuUtilization ( ) ;
45- CPU_COMPUTE_TIMEOUT = setTimeout ( runCpuComputeInterval , Math . max ( CPU_COMPUTE_UTILIZATION_INTERVAL , 1 ) ) ;
48+ if ( CPU_COMPUTE_RUNNING )
49+ CPU_COMPUTE_TIMEOUT = setTimeout ( runCpuComputeInterval , Math . max ( CPU_COMPUTE_UTILIZATION_INTERVAL , 1 ) ) ;
4650}
4751
4852/**
@@ -72,7 +76,7 @@ export function getCpuCoreCount(): number {
7276export async function getCpuCoreUtilization ( ) : Promise < number [ ] > {
7377 if ( ! CPU_COMPUTE_RUNNING ) {
7478 await runCpuComputeInterval ( ) ; // runs the first computation immediately
75- await sleep ( 50 ) ; // wait a bit to get initial values
79+ await sleep ( CPU_COMPUTE_UTILIZATION_INITIAL_DELAY ) ; // wait a bit to get initial values
7680 await computeCpuUtilization ( ) ; // run second computation immediately to get initial values
7781 }
7882 return CPU_CORE_UTILIZATIONS ;
@@ -86,7 +90,7 @@ export async function getCpuCoreUtilization(): Promise<number[]> {
8690export async function getCpuUtilization ( ) : Promise < number > {
8791 if ( ! CPU_COMPUTE_RUNNING ) {
8892 await runCpuComputeInterval ( ) ; // runs the first computation immediately
89- await sleep ( 50 ) ; // wait a bit to get initial values
93+ await sleep ( CPU_COMPUTE_UTILIZATION_INITIAL_DELAY ) ; // wait a bit to get initial values
9094 await computeCpuUtilization ( ) ; // run second computation immediately to get initial values
9195 }
9296 return CPU_UTILIZATION ;
0 commit comments