Method: LinuxStat::ProcessInfo.cpu_stat

Defined in:
lib/linux_stat/process_info.rb

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

cpu_stat(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 LinuxStat::Sysconf.sc_clk_tck

The smallest amount of available sleep time is 1.0 / LinuxStat::Sysconf.sc_clk_tck * 5.

  • Note 1:

  1. Do note that the sleep time can slow down your application.

  2. And it’s only needed for the cpu usage calculation.

It retuns the CPU usage, threads, and the last executed CPU in Hash.

For example:

LinuxStat::ProcessInfo.cpu_stat

=> {:cpu_usage=>0.0, :threads=>1, :last_executed_cpu=>1}

But if the info isn’t available, it will return an empty Hash.

The :cpu_usage is in percentage. It’s also divided with the number of CPU.

:cpu_usage for example, will return 25.0 if the CPU count is 4, and the process is using 100% of a thread / core.

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

The :threads returns the number of threads for the process. The value is a Integer.

  • Note 2:

  1. If you just need the CPU usage run LinuxStat::ProcessInfo.cpu_usage(pid = $$)

  2. If you just need the threads run LinuxStat::ProcessInfo.threads(pid = $$)

  3. If you just need the last executed CPU run LinuxStat::ProcessInfo.last_executed_cpu(pid = $$)

  4. Running this method is slower and it opens multiple files at once

Only use this method if you need all of the data at once, in such case, it’s more efficient to use this method.

The :last_executed_cpu also returns an Integer indicating the last executed cpu of the process.



284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/linux_stat/process_info.rb', line 284

def cpu_stat(pid: $$, sleep: ticks_to_ms_t5)
	file = "/proc/#{pid}/stat"
	ticks = get_ticks

	return {} unless File.readable?(file)

	stat = IO.read(file).split(/(\(.*\))/)[-1] &.split
	return {} unless stat

	utime, stime, starttime = *stat.values_at(11, 12, 19).map(&:to_f)

	uptime = IO.read('/proc/uptime'.freeze).to_f * ticks

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

	sleep(sleep)

	return {} unless File.readable?(file)

	stat = IO.read(file).split(/(\(.*\))/)[-1] &.split
	return {} unless stat

	utime2, stime2, starttime2 = *stat.values_at(11, 12, 19).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)
	cpu_u = totald.-(idle2 - idle1).fdiv(totald).abs.*(100)./(cpu_count)

	{
		cpu_usage: cpu_u > 100 ? 100.0 : cpu_u.round(2),
		threads: stat[17].to_i,
		last_executed_cpu: stat[36].to_i
	}
end