I already found a solution for "Most unixes" via cat /proc/cpuinfo, but a pure-Ruby solution would be nicer.
I already found a solution for "Most unixes" via cat /proc/cpuinfo, but a pure-Ruby solution would be nicer.
EDIT: Now rails ships with concurrent-ruby as a dependency so it's probably the best solution;
$ gem install concurrent-ruby
$ irb
irb(main):001:0> require 'concurrent'
=> true
irb(main):002:0> Concurrent.processor_count
=> 8
irb(main):003:0> Concurrent.physical_processor_count
=> 4
see http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent.html for more info. Because it does both physical and logical cores, it's better than the inbuilt Etc.nprocessors.
and here is the previous answer;
$ gem install facter
$ irb
irb(main):001:0> require 'facter'
=> true
irb(main):002:0> puts Facter.value('processors')['count']
4
=> nil
irb(main):003:0>
This facter gem is the best if you want other facts about the system too, it's not platform specific and designed to do this exact thing.
UPDATE: updated to include Nathan Kleyn's tip on the api change.
with JRuby you can check it with the following Java code:
Runtime runtime = Runtime.getRuntime();
int numberOfProcessors = runtime.availableProcessors();
Surely if you can cat it, you can open, read and close it using the standard features of the language without resorting to a system()-type call.
You may just need to detect what platform you're on dynamically and either:
/proc/cpuinfo "file" for Linux; orThat last line can use:
require 'win32ole'
wmi = WIN32OLE.connect("winmgmts://")
info = wmi.ExecQuery ("select * from Win32_ComputerSystem")
Then use info's NumberOfProcessors item.