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
@grosser:
when /linux/ `grep -c processor /proc/cpuinfo`.to_i
http://www.partmaps.org/era/unix/award.html#cat
http://www.partmaps.org/era/unix/award.html#wc
on Mac:
thiago-pradis-macbook:~ tchandy$ hwprefs cpu_count
2
As of Ruby version 2.2.3, the etc module in Ruby's stdlib offers an nprocessors method which returns the number of processors. The caveat to this, is that if ruby is relegated to a subset of CPU cores, Etc.nprocessors
will only return the number of cores that Ruby has access to. Also, as seanlinsley pointed out, this will only return virtual cores instead of physical cores, which may result in a disparity in the expected value.
require 'etc'
p Etc.nprocessors #=> 4
In linux you can also use nproc
, which is cleaner that the other subshell-based solutions here. I wanted vagrant to give the same number of CPUs to the virtual machine as the host has. I added this to Vagrantfile
:
vb.cpus = `nproc`.to_i
with JRuby you can check it with the following Java code:
Runtime runtime = Runtime.getRuntime();
int numberOfProcessors = runtime.availableProcessors();