Class: Sys::CPU

Inherits:
Object
  • Object
show all
Extended by:
FFI::Library
Defined in:
lib/sys/cpu.rb,
lib/sys/unix/sys/cpu.rb,
lib/sys/linux/sys/cpu.rb,
lib/sys/darwin/sys/cpu.rb,
lib/sys/windows/sys/cpu.rb

Overview

Encapsulates system CPU information

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =

The version of the sys-cpu gem.

'1.3.0'
HOST_OS =
RbConfig::CONFIG['host_os']
CPU_TYPE_ARM64 =
CPU_TYPE_ARM | CPU_ARCH_ABI64

Class Method Summary collapse

Class Method Details

.architecture(host = Socket.gethostname) ⇒ Object

Returns the host CPU's architecture, or nil if it cannot be determined.



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/sys/unix/sys/cpu.rb', line 112

def self.architecture
  if respond_to?(:sysinfo, true)
    buf = 0.chr * 257

    if sysinfo(SI_ARCHITECTURE, buf, buf.size) < 0
      raise Error, 'sysinfo function failed'
    end

    buf.strip
  elsif respond_to?(:sysctlbyname, true)
    optr = FFI::MemoryPointer.new(:char, 256)
    size = FFI::MemoryPointer.new(:size_t)

    size.write_int(optr.size)

    if sysctlbyname('hw.machine_arch', optr, size, nil, 0) < 0
      raise Error, 'sysctlbyname function failed'
    end

    optr.read_string
  else
    buf  = 0.chr * 64
    mib  = FFI::MemoryPointer.new(:int, 2)
    size = FFI::MemoryPointer.new(:long, 1)

    mib.write_array_of_int([CTL_HW, HW_MACHINE_ARCH])
    size.write_int(buf.size)

    if sysctl(mib, 2, buf, size, nil, 0) < 0
      raise Error, 'sysctl function failed'
    end

    buf.strip
  end
end

.cpu_statsObject

Returns a hash of arrays that contains an array of the following information (as of 2.6.33), respectively:

  • user: time spent in user mode.
  • nice: time spent in user mode with low priority.
  • system: time spent in system mode.
  • idle: time spent in the idle task.
  • iowait: time waiting for IO to complete.
  • irq: time servicing interrupts.
  • softirq: time servicing softirqs.
  • steal: time spent in other operating systems when running in a virtualized environment.
  • guest: time spent running a virtual CPU for guest operating systems.
  • guest_nice: time spent running a niced guest, i.e a virtual CPU for guest operating systems.

Note that older kernels may not necessarily include some of these fields.



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/sys/linux/sys/cpu.rb', line 218

def self.cpu_stats
  cpu_stat_file = '/proc/stat'
  hash = {} # Hash needed for multi-cpu systems

  lines = File.readlines(cpu_stat_file)

  lines.each_with_index do |line, i|
    array = line.split
    break unless array[0] =~ /cpu/ # 'cpu' entries always on top

    # Some machines list a 'cpu' and a 'cpu0'. In this case only
    # return values for the numbered cpu entry.
    if lines[i].split[0] == 'cpu' && lines[i + 1].split[0] =~ /cpu\d/
      next
    end

    # Keep raw jiffies counts (do not scale by hz) so deltas over short
    # intervals still produce meaningful values.
    vals = array[1..-1].map{ |e| e.to_i }
    hash[array[0]] = vals
  end

  hash
end

.cpu_type(host = Socket.gethostname) ⇒ Object

Returns a string indicating the type of processor, e.g. GenuineIntel.



300
301
302
303
304
305
306
307
308
309
# File 'lib/sys/windows/sys/cpu.rb', line 300

def self.cpu_type(host = Socket.gethostname)
  cs = BASE_CS + "//#{host}/root/cimv2:Win32_Processor='cpu0'"
  begin
    wmi = WIN32OLE.connect(cs)
  rescue WIN32OLERuntimeError => err
    raise Error, err
  else
    wmi.Manufacturer
  end
end

.cpu_usage(sample_time: 1.0, samples: 2, cpu_num: 0, host: Socket.gethostname) ⇒ Object

Returns CPU usage as a percentage, averaged over multiple samples.

The sample_time keyword specifies the interval (in seconds) between samples. The samples keyword specifies how many samples to take and average. The cpu_num keyword selects which CPU to query (0 for total). The host keyword specifies the target machine (defaults to local).

-- This method uses the _Total Win32_PerfFormattedData_PerfOS_Processor instance (unless a specific cpu_num is requested) to better match Task Manager's total view.

Note: Task Manager reports total CPU usage across all cores. Win32_Processor.LoadPercentage is per-processor (usually per physical socket), so it can differ from Task Manager if it falls back.



318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/sys/unix/sys/cpu.rb', line 318

def self.cpu_usage(sample_time: 1.0, samples: 2)
  cp_time = proc { |ptr|
    len = 5
    size = FFI::MemoryPointer.new(:size_t)
    size.write_ulong(ptr.size)

    if sysctlbyname('kern.cp_time', ptr, size, nil, 0) < 0
      raise Error, 'sysctlbyname failed'
    end

    ptr.read_array_of_ulong(len)
  }

  sample_time = 1.0 if sample_time.nil? || sample_time <= 0
  samples = 2 if samples.nil? || samples <= 0

  usages = []

  samples.times do
    t1 = cp_time.call(FFI::MemoryPointer.new(:ulong, 5))
    sleep(sample_time)
    t2 = cp_time.call(FFI::MemoryPointer.new(:ulong, 5))

    total1 = t1.sum
    total2 = t2.sum
    idle1 = t1[4] || 0
    idle2 = t2[4] || 0

    total_diff = total2 - total1
    idle_diff = idle2 - idle1

    usages << ((1.0 - (idle_diff.to_f / total_diff)) * 100) if total_diff > 0
  end

  return nil if usages.empty?
  (usages.sum / usages.size.to_f).round(1)
rescue StandardError
  nil
end

.fpu_typeObject

Returns the floating point processor type.

Not supported on all platforms.

Raises:

  • (NoMethodError)


362
363
364
365
366
367
368
369
370
371
372
373
# File 'lib/sys/unix/sys/cpu.rb', line 362

def self.fpu_type
  raise NoMethodError unless respond_to?(:processor_info, true)

  pinfo = ProcInfo.new

  # Some start at 0, some start at 1
  if processor_info(0, pinfo) < 0 && processor_info(1, pinfo) < 0
    raise Error, 'processor_info function failed'
  end

  pinfo[:pi_fputypes].to_s
end

.freq(cpu_num = 0, host = Socket.gethostname) ⇒ Object

Returns an integer indicating the speed (i.e. frequency in Mhz) of cpu_num on host, or the localhost if no host is specified. If cpu_num +1 is greater than the number of cpu's on your system or this call fails for any other reason, a Error is raised.



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/sys/unix/sys/cpu.rb', line 255

def self.freq
  if respond_to?(:sysctlbyname, true)
    optr = FFI::MemoryPointer.new(:long)
    size = FFI::MemoryPointer.new(:size_t)

    size.write_long(optr.size)

    if HOST_OS =~ /bsd|dragonfly/i
      if architecture =~ /aarch/i
        name = 'kern.hz'
      else
        name = 'hw.clockrate'
      end
    else
      name = 'hw.cpufrequency'
    end

    if sysctlbyname(name, optr, size, nil, 0) < 0
      raise Error, 'sysctlbyname failed'
    end

    optr.read_long
  elsif respond_to?(:sysctl, true)
    buf  = 0.chr * 16
    mib  = FFI::MemoryPointer.new(:int, 2)
    size = FFI::MemoryPointer.new(:long, 1)

    mib.write_array_of_int([CTL_HW, HW_CPU_FREQ])
    size.write_int(buf.size)

    if sysctl(mib, 2, buf, size, nil, 0) < 0
      raise Error, 'sysctl function failed'
    end

    buf.unpack1('I*') / 1_000_000
  else
    pinfo = ProcInfo.new

    # Some systems start at 0, some at 1
    if processor_info(0, pinfo) < 0 && processor_info(1, pinfo) < 0
      raise Error, 'processor_info function failed'
    end

    pinfo[:pi_clock].to_i
  end
end

.load_avg(cpu_num = 0, host = Socket.gethostname) ⇒ Object

Returns the load capacity for cpu_num on host, or the localhost if no host is specified, averaged to the last second. Processor loading refers to the total computing burden for each processor at one time.

Note that this attribute is actually the LoadPercentage. I may use one of the Win32_Perf* classes in the future.



305
306
307
308
309
310
# File 'lib/sys/unix/sys/cpu.rb', line 305

def self.load_avg
  return unless respond_to?(:getloadavg, true)
  loadavg = FFI::MemoryPointer.new(:double, 3)
  raise Error, 'getloadavg function failed' if getloadavg(loadavg, loadavg.size) < 0
  loadavg.get_array_of_double(0, 3)
end

.machineObject

Returns the cpu's class type. On most systems this will be identical to the CPU.architecture method. On OpenBSD it will be identical to the CPU.model method.



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/sys/unix/sys/cpu.rb', line 192

def self.machine
  if respond_to?(:sysctl, true)
    buf  = 0.chr * 32
    mib  = FFI::MemoryPointer.new(:int, 2)
    size = FFI::MemoryPointer.new(:long, 1)

    mib.write_array_of_int([CTL_HW, HW_MACHINE])
    size.write_int(buf.size)

    if sysctl(mib, 2, buf, size, nil, 0) < 0
      raise Error, 'sysctl function failed'
    end
  else
    buf = 0.chr * 257

    if sysinfo(SI_MACHINE, buf, buf.size) < 0
      raise Error, 'sysinfo function failed'
    end
  end

  buf.strip
end

.model(host = Socket.gethostname) ⇒ Object

Returns a string indicating the cpu model, e.g. Intel Pentium 4.



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/sys/unix/sys/cpu.rb', line 217

def self.model
  if respond_to?(:sysctl, true)
    buf  = 0.chr * 64
    mib  = FFI::MemoryPointer.new(:int, 2)
    size = FFI::MemoryPointer.new(:long, 1)

    mib.write_array_of_int([CTL_HW, HW_MODEL])
    size.write_int(buf.size)

    if sysctl(mib, 2, buf, size, nil, 0) < 0
      raise Error, 'sysctl function failed'
    end

    buf.strip
  else
    pinfo = ProcInfo.new

    # Some systems start at 0, some at 1
    if processor_info(0, pinfo) < 0 && processor_info(1, pinfo) < 0
      raise Error, 'processor_info function failed'
    end

    pinfo[:pi_processor_type].to_s
  end
end

.num_cpu(host = Socket.gethostname) ⇒ Object

Returns an integer indicating the number of cpu's on the system.

This (oddly) requires a different class.



152
153
154
155
156
157
158
159
160
161
162
163
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/sys/unix/sys/cpu.rb', line 152

def self.num_cpu
  if respond_to?(:sysctlbyname, true)
    optr = FFI::MemoryPointer.new(:long)
    size = FFI::MemoryPointer.new(:size_t)

    size.write_long(optr.size)

    if sysctlbyname('hw.ncpu', optr, size, nil, 0) < 0
      raise Error, 'sysctlbyname failed'
    end

    optr.read_long
  elsif respond_to?(:sysconf, true)
    num = sysconf(SC_NPROCESSORS_ONLN)

    if num < 0
      raise Error, 'sysconf function failed'
    end

    num
  else
    buf  = 0.chr * 4
    mib  = FFI::MemoryPointer.new(:int, 2)
    size = FFI::MemoryPointer.new(:long, 1)

    mib.write_array_of_int([CTL_HW, HW_NCPU])
    size.write_int(buf.size)

    if sysctl(mib, 2, buf, size, nil, 0) < 0
      raise Error, 'sysctl function failed'
    end

    buf.strip.unpack1('C')
  end
end

.processors(host = Socket.gethostname) ⇒ Object

Returns a CPUStruct for each CPU on host, or the localhost if no host is specified. A CPUStruct contains the following members:

  • address_width
  • architecture
  • availability
  • caption
  • config_manager_error_code
  • config_manager_user_config
  • cpu_status
  • creation_class_name
  • freq
  • voltage
  • data_width
  • description
  • device_id
  • error_cleared?
  • error_description
  • ext_clock
  • family
  • install_date
  • l2_cache_size
  • l2_cache_speed
  • last_error_code
  • level
  • load_avg
  • manufacturer
  • max_clock_speed
  • name
  • other_family_description
  • pnp_device_id
  • power_management_supported?
  • power_management_capabilities
  • processor_id
  • processor_type
  • revision
  • role
  • socket_designation
  • status
  • status_info
  • stepping
  • system_creation_class_name
  • system_name
  • unique_id
  • upgrade_method
  • version
  • voltage_caps

Note that not all of these members will necessarily be defined.

rubocop:disable Metrics/BlockLength



62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/sys/linux/sys/cpu.rb', line 62

def self.processors
  array = []
  CPU_ARRAY.each do |hash|
    struct = CPUStruct.new
    struct.members.each{ |m| struct.send("#{m}=", hash[m.to_s]) }
    if block_given?
      yield struct
    else
      array << struct
    end
  end
  array unless block_given?
end

.respond_to_missing?(method, _private_methods = false) ⇒ Boolean

Returns:

  • (Boolean)


188
189
190
# File 'lib/sys/linux/sys/cpu.rb', line 188

def self.respond_to_missing?(method, _private_methods = false)
  CPU_ARRAY.first.keys.include?(method.to_s)
end

.state(num = 0) ⇒ Object

Returns the current state of processor num, or 0 if no number is specified.

Not supported on all platforms.

Raises:

  • (NoMethodError)


380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'lib/sys/unix/sys/cpu.rb', line 380

def self.state(num = 0)
  raise NoMethodError unless respond_to?(:processor_info, true)

  pinfo = ProcInfo.new

  if processor_info(num, pinfo) < 0
    raise Error, 'processor_info function failed'
  end

  case pinfo[:pi_state].to_i
    when P_ONLINE
      'online'
    when P_OFFLINE
      'offline'
    when P_POWEROFF
      'poweroff'
    when P_FAULTED
      'faulted'
    when P_NOINTR
      'nointr'
    when P_SPARE
      'spare'
    else
      'unknown'
  end
end