Method: LinuxStat::ProcessInfo.cpu_stat

Defined in:
lib/linux_stat/process_info.rb

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

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

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

  • 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.



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/linux_stat/process_info.rb', line 247

def cpu_stat(pid: $$, sleep: ticks_to_ms)
	file = "/proc/#{pid}/stat"
	return {} 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)
	stat = IO.read(file).split

	utime2, stime2, starttime2 = stat.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)
	cpu = totald.-(idle2 - idle1).fdiv(totald).*(100).round(2).abs./(LinuxStat::CPU.count)

	{
		cpu_usage: cpu,
		threads: stat[19].to_i,
		last_executed_cpu: stat[38].to_i
	}
end