Module: LinuxStat::CPU

Defined in:
lib/linux_stat/cpu.rb

Overview

Shows various CPU related information of the current system.

Class Method Summary collapse

Class Method Details

.available_governorsObject

Returns an array of governors for each CPU as a Hash.

For example:

LinuxStat::CPU.available_governors

=> {"cpu0"=>["performance", "powersave"], "cpu1"=>["performance", "powersave"], "cpu2"=>["performance", "powersave"], "cpu3"=>["performance", "powersave"]}

If the information isn’t available, it will return an empty Hash.



323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/linux_stat/cpu.rb', line 323

def available_governors
	@@scaling_av_g ||= cpus.map { |x|
		[File.split(x)[-1], File.join(x, 'cpufreq/scaling_available_governors'.freeze)]
	}

	h = {}
	@@scaling_av_g.each { |id, file|
		h.store(id, IO.read(file).split.each(&:strip!)) if File.readable?(file)
	}

	h
end

.countObject

Returns the total number of CPU available for the sysetm.

It returns an Integer.

If the information isn’t available, it will return nil.



118
119
120
# File 'lib/linux_stat/cpu.rb', line 118

def count
	@@cpu_count ||= LinuxStat::Sysconf.processor_configured
end

.count_onlineObject

Returns the total number of CPU online in the sysetm.

It first reads /proc/stat, if that fails, it will read /sys/devices/system/cpu/online, if that fails it will open /proc/cpuinfo. If neither of the procedures work, it will get the LinuxStat::Sysconf.processor_online

It opens /sys/devices/system/cpu/offline and performs various job to get one Ruby array.

If the information isn’t available, it will return an empty Array.



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/linux_stat/cpu.rb', line 135

def count_online
	@@cpuinfo_file ||= '/proc/cpuinfo'.freeze
	@@cpuinfo_readable ||= File.readable?(@@cpuinfo_file)

	@@stat_file ||= '/proc/stat'.freeze

	# Not much slow, not blazing fast, somewhat reliable
	get_online = online

	if !get_online.empty?
		get_online.length
	elsif @@cpuinfo_readable
		# Way slower but reliable!
		IO.readlines(@@cpuinfo_file).count { |x| x.strip[/\Aprocessor.*\d*\z/] }
	else
		# Way faster but absolutely unrealiable!
		LinuxStat::Sysconf.processor_online
	end
end

.cur_freqObject

Returns a Hash with current core frequencies corresponding to the CPUs.

For example:

LinuxStat::CPU.cur_freq

=> {"cpu0"=>1999990, "cpu1"=>2000042, "cpu2"=>2000016, "cpu3"=>2000088}

If the information isn’t available, it will return an empty Hash.



229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/linux_stat/cpu.rb', line 229

def cur_freq
	@@cur_f ||= cpus.map { |x|
		[File.split(x)[-1], File.join(x, 'cpufreq/scaling_cur_freq'.freeze)]
	}

	h = {}
	@@cur_f.each { |id, file|
		h.store(id, IO.read(file).to_i) if File.readable?(file)
	}

	h
end

.governorObject

Returns the corresponding governor of each CPU.

The return type is a Hash.

For example:

LinuxStat::CPU.governor

=> {"cpu0"=>"powersave", "cpu1"=>"powersave", "cpu2"=>"performance", "cpu3"=>"performance"}

If the information isn’t available, it will return an empty Hash.



301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/linux_stat/cpu.rb', line 301

def governor
	@@scaling_g ||= cpus.map { |x|
		[File.split(x)[-1], File.join(x, 'cpufreq/scaling_governor'.freeze)]
	}

	h = {}
	@@scaling_g.each { |id, file|
		h.store(id, IO.read(file).tap(&:strip!)) if File.readable?(file)
	}

	h
end

.hyperthreaded_core_listObject Also known as: hyperthreaded_cores

Returns the number of physical cores on the system.

The return value is an Array of Integers. Each number denoting the hyperthreaded processor number. You can later use this to schedule tasks or something else (not provided by LinuxStat).

However, if the information isn’t available on /sys/devices/system/cpu*/topology/thread_siblings_list, it will return an empty Array.



384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'lib/linux_stat/cpu.rb', line 384

def hyperthreaded_core_list
	hyperthreaded = {}

	return [] unless File.executable?('/sys/devices/system/cpu/'.freeze)
	entries = Dir.entries('/sys/devices/system/cpu/'.freeze)
	entries.delete(?..freeze)
	entries.delete('..'.freeze)

	entries.each do |x|
		if x[0..2] == 'cpu'.freeze && LinuxStat::Misc.integer?(x[3..-1])
			file = "/sys/devices/system/cpu/#{x}/topology/thread_siblings_list"
			next unless File.readable?(file)

			data = IO.read(file)
			data.strip!

			val = data.split(?,.freeze).map(&:to_i)
			val.shift

			# Add items has for fast lookup to get rid of duplicate items.
			val.each { |x| hyperthreaded.store(x, nil) unless hyperthreaded.key?(x) }
		end
	end

	hyperthreaded.keys
end

.max_freqObject

Returns a Hash with max core frequencies corresponding to the CPUs.

For example:

LinuxStat::CPU.max_freq

=> {"cpu0"=>2000000, "cpu1"=>2000000, "cpu2"=>2000000, "cpu3"=>2000000}

If the information isn’t available, it will return an empty Hash.



277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/linux_stat/cpu.rb', line 277

def max_freq
	@@min_f ||= cpus.map { |x|
		[File.split(x)[-1], File.join(x, 'cpufreq/scaling_max_freq'.freeze)]
	}

	h = {}
	@@min_f.each { |id, file|
		h.store(id, IO.read(file).to_i) if File.readable?(file)
	}

	h
end

.min_freqObject

Returns a Hash with max core frequencies corresponding to the CPUs.

For example:

LinuxStat::CPU.min_freq

=> {"cpu0"=>2000000, "cpu1"=>2000000, "cpu2"=>2000000, "cpu3"=>2000000}

If the information isn’t available, it will return an empty Hash.



255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/linux_stat/cpu.rb', line 255

def min_freq
	@@min_f ||= cpus.map { |x|
		[File.split(x)[-1], File.join(x, 'cpufreq/scaling_min_freq'.freeze)]
	}

	h = {}
	@@min_f.each { |id, file|
		h.store(id, IO.read(file).to_i) if File.readable?(file)
	}

	h
end

.modelObject

Returns the model of processor.

If the information isn’t available, it will return en empty string.

The output is also cached (memoized) ; as changing the value in runtime is unexpected.



216
217
218
# File 'lib/linux_stat/cpu.rb', line 216

def model
	@@name ||= cpuinfo.find { |x| x.start_with?('model name') }.to_s.split(?:)[-1].to_s.strip
end

.offlineObject

Returns the total number of CPU offline in the sysetm.

It opens /sys/devices/system/cpu/offline and performs various job to get one Ruby array.

If the information isn’t available, it will return an empty Array.



195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/linux_stat/cpu.rb', line 195

def offline
	@@offline_file ||= '/sys/devices/system/cpu/offline'.freeze
	@@offline_readable ||= File.readable?(@@offline_file)
	return [] unless @@offline_readable

	ret = []
	IO.read(@@offline_file).split(?,.freeze).each { |x|
		x.strip!
		c = x.split(?-.freeze).map(&:to_i)
		ret.concat(c.length == 2 ? Range.new(*c).to_a : c)
	}

	ret
end

.onlineObject

Returns the total number of CPU online in the sysetm.

It will read /proc/stat to get the info.

If the info isn’t available, it reads /sys/devices/system/cpu/onfline and performs various job to get one Ruby array.

If the information isn’t available, it will return an empty Array.



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/linux_stat/cpu.rb', line 164

def online
	@@online_file ||= '/sys/devices/system/cpu/online'.freeze
	@@online_readable ||= File.readable?(@@online_file)

	@@stat_file ||= '/proc/stat'.freeze

	ret = []

	if stat?
		IO.readlines(@@stat_file).map { |x|
			v = x.strip[/\Acpu\d*/] &.[](/\d/)
			ret << v.to_i if v
		}
	elsif @@online_readable
		IO.read(@@online_file).split(?,.freeze).each { |x|
			x.strip!
			c = x.split(?-.freeze).map(&:to_i)
			ret.concat(c.length == 2 ? Range.new(*c).to_a : c)
		}
	end

	ret
end

.physical_core_listObject Also known as: physical_cores

Returns the number of physical cores on the system.

The return value is an Array of Integers. Each number denoting the physical processor number. You can later use this to schedule tasks or something else (not provided by LinuxStat).

However, if the information isn’t available on /sys/devices/system/cpu*/topology/thread_siblings_list, it will return an empty Array.



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
369
370
371
372
373
374
375
# File 'lib/linux_stat/cpu.rb', line 343

def physical_core_list
	physical_cores = []
	hyperthreaded = {}

	return [] unless File.executable?('/sys/devices/system/cpu/'.freeze)
	entries = Dir.entries('/sys/devices/system/cpu/'.freeze)
	entries.delete(?..freeze)
	entries.delete('..'.freeze)

	entries.each do |x|
		if x[0..2] == 'cpu'.freeze && LinuxStat::Misc.integer?(x[3..-1])
			file = "/sys/devices/system/cpu/#{x}/topology/thread_siblings_list"
			next unless File.readable?(file)

			data = IO.read(file)
			data.strip!

			val = data.split(?,.freeze).map(&:to_i)
			val.shift

			# Add items has for fast lookup.
			# This hash includes all hyper threaded cores that doesn't map to anything.
			# But this hash has the purpose to look up for items and not include in the list of physical_cores
			# This is just an array, but can look for keys in O(1), so it's faster than ary.find() { ... }.
			val.each { |x| hyperthreaded.store(x, nil) }

			key = x[3..-1].to_i
			physical_cores << key unless hyperthreaded.key?(key)
		end
	end

	physical_cores
end

.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

.timesObject



242
243
244
# File 'lib/linux_stat/cpu.rb', line 242

def times
	LinuxStat::ProcFS.cpu_times
end

.total_usage(sleep = ticks_to_ms_t5) ⇒ Object Also known as: usage

total_usage(sleep = 1.0 / LinuxStat::Sysconf.sc_clk_tck)

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.

It’s like running LinuxStat::CPU.stat but it’s much more efficient and calculates just the aggregated usage which is available at the top of the /proc/stat file.

If the information is not available, it will return nil.



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/linux_stat/cpu.rb', line 95

def total_usage(sleep = ticks_to_ms_t5)
	return nil unless stat?

	data = IO.foreach('/proc/stat'.freeze).first.split.tap(&:shift).map!(&:to_f)
	sleep(sleep)
	data2 = IO.foreach('/proc/stat'.freeze).first.split.tap(&:shift).map!(&:to_f)

	user, nice, sys, idle, iowait, irq, softirq, steal = *data
	user2, nice2, sys2, idle2, iowait2, irq2, softirq2, steal2 = *data2

	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)

	u = totald.-(idle_now - idle_then).fdiv(totald).abs.*(100)
	u > 100 ? 100.0 : u.round(2)
end