Skip to content

Instantly share code, notes, and snippets.

@jimweirich
Last active December 18, 2015 16:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jimweirich/5813834 to your computer and use it in GitHub Desktop.
Save jimweirich/5813834 to your computer and use it in GitHub Desktop.
Can people run this script and see if it gives accurate count of CPUs on their system. Report results in the comments please. Thanks! Oh! And don't forget to report what kind of system you are running this on (linux, windows, mac, etc.). UPDATE: Revised version that uses the Java runtime if running under JRuby.
require 'rbconfig'
# Based on a script at:
# http://stackoverflow.com/questions/891537/ruby-detect-number-of-cpus-installed
class CpuCounter
def self.count
new.count
end
def count
if defined?(Java::Java)
count_via_java_runtime
else
case RbConfig::CONFIG['host_os']
when /darwin9/
count_via_hwprefs_cpu_count
when /darwin/
count_via_hwprefs_thread_count || count_via_sysctl
when /linux/
count_via_cpuinfo
when /freebsd/
count_via_sysctl
when /mswin|mingw/
count_via_win32
end
end
end
def count_via_java_runtime
Java::Java.lang.Runtime.getRuntime.availableProcessors
end
def count_via_win32
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
def count_via_cpuinfo
open('/proc/cpuinfo') { |f| f.readlines }.grep(/processor/).size
end
def count_via_hwprefs_thread_count
run 'hwprefs', 'thread_count'
end
def count_via_hwprefs_cpu_count
run 'hwprefs', 'cpu_count'
end
def count_via_sysctl
run 'sysctl', '-n hw.ncpu'
end
def run(command, args)
cmd = resolve_command(command)
if cmd
`#{cmd} #{args}`.to_i
else
nil
end
end
def resolve_command(command)
try_command("/sbin", command) ||
try_command("/usr/sbin", command) ||
in_path_command(command)
end
def try_command(dir, command)
path = File.join(dir, command)
File.exist?(path) ? path : nil
end
def in_path_command(command)
`which #{command}` != '' ? command : nil
end
end
if $0 == __FILE__
puts "Number of CPUs = #{CpuCounter.count}"
end
@carlosipe
Copy link

Looks correct here too:

$ ruby cpu.rb
Number of CPUs = 8
$ uname -a
Linux notebook 3.2.0-29-generic #46-Ubuntu SMP Fri Jul 27 17:03:23 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment