I already found a solution for \"Most unixes\" via cat /proc/cpuinfo
, but a pure-Ruby solution would be nicer.
Here is an implementation for Linux, OSX, Windows and BSD: https://gist.github.com/1009994
Source code:
module System
extend self
def cpu_count
return Java::Java.lang.Runtime.getRuntime.availableProcessors if defined? Java::Java
return File.read('/proc/cpuinfo').scan(/^processor\s*:/).size if File.exist? '/proc/cpuinfo'
require 'win32ole'
WIN32OLE.connect("winmgmts://").ExecQuery("select * from Win32_ComputerSystem").NumberOfProcessors
rescue LoadError
Integer `sysctl -n hw.ncpu 2>/dev/null` rescue 1
end
end
System.cpu_count # => 2