Method: LinuxStat::ProcessInfo.cpu_usage

Defined in:
lib/linux_stat/process_info.rb

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

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

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 * 5

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

It retuns the CPU usage as Float.

For example:

LinuxStat::ProcessInfo.cpu_usage

=> 10.0

10.0 means it’s using 10% of the total processing power of the system.

The value is divided with the configured number of CPU and not online CPU.

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()



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/linux_stat/process_info.rb', line 340

def cpu_usage(pid: $$, sleep: ticks_to_ms_t5)
	ticks = get_ticks
	stat = LinuxStat::ProcFS.ps_stat(pid)
	uptime = LS::ProcFS.uptime_f
	return nil unless uptime && !stat.empty?

	utime, stime, starttime = *stat.values_at(10, 11, 18).map(&:to_f)
	uptime *= ticks

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

	sleep(sleep)

	stat = LinuxStat::ProcFS.ps_stat(pid)
	uptime = LS::ProcFS.uptime_f
	return nil unless uptime && !stat.empty?

	utime2, stime2, starttime2 = *stat.values_at(10, 11, 18).map(&:to_f)
	uptime *= ticks

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

	totald = idle2.+(total_time2).-(idle1 + total_time)

	u = totald.-(idle2 - idle1).fdiv(totald).abs.*(100)./(cpu_count)
	u > 100 ? 100.0 : u.round(2)
end