Method: LinuxStat::CPU.stat
- Defined in:
- lib/linux_stat/cpu.rb
.stat(sleep = ticks_to_ms_t5) ⇒ Object Also known as: usages
stat(sleep = 1.0 / LinuxStat::Sysconf.sc_clk_tck * 5)
Where sleep is the delay to gather the data.
The minimum possible value at anytime is 1.0 / LinuxStat::Sysconf.sc_clk_tck
This method returns the cpu usage of all threads.
The first one is aggregated CPU usage reported by the Linux kernel.
And the consecutive ones are the real core usages.
For example, on a system with 4 threads:
LinuxStat::CPU.stat
=> {0=>84.38, 1=>100.0, 2=>50.0, 3=>87.5, 4=>87.5}
It discards any offline CPU or disabled CPU. For example, if your system CPU has 4 cores, and you disabled core 3, the output will be:
LinuxStat::CPU.stat
=> {0=>26.67, 1=>0.0, 2=>20.0, 4=>20.0}
If the information is not available, it will return an empty Hash
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/linux_stat/cpu.rb', line 31 def stat(sleep = ticks_to_ms_t5) return {} unless stat? data = IO.readlines('/proc/stat'.freeze).select { |x| x[/^cpu\d*/] } cpu_names1 = [] data.map! { |x| splitted = x.split name = splitted.shift[/\d*$/] cpu_names1.push(name.empty? ? 0 : name.to_i + 1) splitted.map!(&:to_f) } sleep(sleep) data2 = IO.readlines('/proc/stat'.freeze).select { |x| x[/^cpu\d*/] } cpu_names2 = [] data2.map! { |x| splitted = x.split name = splitted.shift[/\d*$/] cpu_names2.push(name.empty? ? 0 : name.to_i + 1) splitted.map!(&:to_f) } # On devices like android, the core count can change anytime (hotplugging). # I had crashes on Termux. # So better just count the min number of CPU and iterate over that # If data.length is smaller than data2.length, we don't have enough data to compare. dl, d2l = cpu_names1.length, cpu_names2.length if dl > d2l min = d2l cpu_cores = cpu_names2 else min = dl cpu_cores = cpu_names1 end min.times.reduce({}) do |h, x| cpu_core = cpu_cores[x] user, nice, sys, idle, iowait, irq, softirq, steal = *data[x] user2, nice2, sys2, idle2, iowait2, irq2, softirq2, steal2 = *data2[x] idle_then, idle_now = idle + iowait, idle2 + iowait2 totald = idle_now.+(user2 + nice2 + sys2 + irq2 + softirq2 + steal2) - idle_then.+(user + nice + sys + irq + softirq + steal) res = totald.-(idle_now - idle_then).fdiv(totald).abs.*(100) res = res.nan? ? 0.0 : res > 100 ? 100.0 : res.round(2) h.store(cpu_core, res) h end end |