44import { useEffect , useState } from "react"
55import { Progress , Switch } from 'antd' ;
66import { useApp } from "../context/appContext" ;
7+ import useInterval from "./useInterval" ;
78const Stats = ( ) => {
89 const [ memoryPercentage , setMemoryrcentage ] = useState ( false )
9- const [ cpuPercentage , setCpuPercentage ] = useState ( false )
10+ const [ cpuPercentage , setCpuPercentage ] = useState ( 0 )
11+ const [ previousCpuInfo , setPreviousCpuInfo ] = useState ( false )
12+
1013 const { theme, switchTeme } = useApp ( )
1114
1215 // load memory and cpu usage from chrome apis
@@ -18,22 +21,30 @@ const Stats = () => {
1821 } ) ;
1922
2023 chrome . system . cpu . getInfo ( function ( info ) {
21- let totalUsage = info . processors . reduce ( ( acc , el , index ) => {
22- let used = Math . floor ( ( el . usage . kernel + el . usage . user ) / el . usage . total * 100 ) ;
23- acc += used
24- return acc
25- } , 0 )
26- setCpuPercentage ( totalUsage )
24+ let totalp = 0
25+ info . processors . forEach ( ( el , index ) => {
26+ let percentage = 0 ;
27+ let usage = el . usage ;
28+ if ( previousCpuInfo ) {
29+ let oldUsage = previousCpuInfo . processors [ index ] . usage ;
30+ percentage = Math . floor ( ( usage . kernel + usage . user - oldUsage . kernel - oldUsage . user ) / ( usage . total - oldUsage . total ) * 100 ) ;
31+ } else {
32+ percentage = Math . floor ( ( usage . kernel + usage . user ) / usage . total * 100 ) ;
33+ }
34+ totalp += percentage
35+ } )
36+ let p = Math . floor ( totalp / info . processors . length )
37+ if ( p > 0 ) {
38+ setCpuPercentage ( p ) // prevent flashing
39+ }
40+ setPreviousCpuInfo ( info )
41+
2742 } ) ;
2843 }
2944
30- useEffect ( ( ) => {
45+ useInterval ( ( ) => {
3146 loadData ( )
32- const interval = setInterval ( ( ) => {
33- loadData ( )
34- } , 1000 ) ;
35- return ( ) => clearInterval ( interval ) ;
36- } , [ ] )
47+ } , 1000 ) ;
3748
3849
3950 return (
0 commit comments