Method: LinuxStat::ProcessInfo.cpu_usage

Defined in:
lib/linux_stat/process_info.rb

.cpu_usage(pid: $$, sleep: ticks_to_ms) ⇒ Object

cpu_usage(pid: $$, sleep: 1.0 / LinuxStat::Sysconf.sc_clk_tck)

Where pid is the process ID and sleep time is the interval between measurements.

By default it is the id of the current process ($$), and sleep is 1.0 / LinuxStat::Sysconf.sc_clk_tck

The smallest amount of available sleep time is LinuxStat::Sysconf.sc_clk_tck.

It retuns the CPU usage in Float.

For example:

LinuxStat::ProcessInfo.cpu_usage

=> 10.0

A value of 100.0 indicates it is using 100% processing power available to the system.

But if the info isn’t available, it will return nil.

This method is more efficient than running LinuxStat::ProcessInfo.cpu_stat()



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/linux_stat/process_info.rb', line 301

def cpu_usage(pid: $$, sleep: ticks_to_ms)
	file = "/proc/#{pid}/stat"
	return nil unless File.readable?(file)

	ticks = get_ticks

	utime, stime, starttime = IO.read(file)
		.split.values_at(13, 14, 21).map(&:to_f)
	uptime = IO.read('/proc/uptime'.freeze).to_f * ticks

	total_time = utime + stime
	idle1 = uptime - starttime - total_time

	sleep(sleep)

	utime2, stime2, starttime2 = IO.read(file)
		.split.values_at(13, 14, 21).map(&:to_f)
	uptime = IO.read('/proc/uptime'.freeze).to_f * ticks

	total_time2 = utime2 + stime2
	idle2 = uptime - starttime2 - total_time2

	totald = idle2.+(total_time2).-(idle1 + total_time)
	totald.-(idle2 - idle1).fdiv(totald).*(100).round(2).abs./(LinuxStat::CPU.count)
end