Class: Nyara::CpuCounter

Inherits:
Object show all
Defined in:
lib/nyara/cpu_counter.rb

Overview

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.countObject


8
9
10
# File 'lib/nyara/cpu_counter.rb', line 8

def self.count
  new.count
end

Instance Method Details

#countObject


12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/nyara/cpu_counter.rb', line 12

def count
  case RbConfig::CONFIG['host_os']
  when /darwin9/
    `hwprefs cpu_count`.to_i
  when /darwin/
    darwin_count
  when /linux/
    linux_count
  when /freebsd/
    freebsd_count
  when /mswin|mingw/
    win32_count
  end
end

#darwin_countObject


27
28
29
30
31
32
33
# File 'lib/nyara/cpu_counter.rb', line 27

def darwin_count
  if cmd = resolve_command('hwprefs')
    `#{cmd} thread_count`.to_i
  elsif cmd = resolve_command('sysctl')
    `#{cmd} -n hw.ncpu`.to_i
  end
end

#freebsd_countObject


39
40
41
42
43
# File 'lib/nyara/cpu_counter.rb', line 39

def freebsd_count
  if cmd = resolve_command('sysctl')
    `#{cmd} -n hw.ncpu`.to_i
  end
end

#in_path_command(command) ⇒ Object


56
57
58
# File 'lib/nyara/cpu_counter.rb', line 56

def in_path_command(command)
  `which #{command}` != '' ? command : nil
end

#linux_countObject


35
36
37
# File 'lib/nyara/cpu_counter.rb', line 35

def linux_count
  open('/proc/cpuinfo') { |f| f.readlines }.grep(/processor/).size
end

#resolve_command(command) ⇒ Object


52
53
54
# File 'lib/nyara/cpu_counter.rb', line 52

def resolve_command(command)
  try_command("/sbin/", command) || try_command("/usr/sbin/", command) || in_path_command(command)
end

#try_command(dir, command) ⇒ Object


60
61
62
63
# File 'lib/nyara/cpu_counter.rb', line 60

def try_command(dir, command)
  path = dir + command
  File.exist?(path) ? path : nil
end

#win32_countObject


45
46
47
48
49
50
# File 'lib/nyara/cpu_counter.rb', line 45

def win32_count
  require 'win32ole'
  wmi = WIN32OLE.connect("winmgmts://")
  cpu = wmi.ExecQuery("select NumberOfCores from Win32_Processor") # TODO count hyper-threaded in this
  cpu.to_enum.first.NumberOfCores
end