I already found a solution for "Most unixes" via cat /proc/cpuinfo
, but a pure-Ruby solution would be nicer.
Press Ctrl + Shift + Esc to open Task Manager. Select the Performance tab to see how many cores and logical processors your PC has.
You can use one of the following command to find the number of physical CPU cores including all cores on Linux: lscpu command. cat /proc/cpuinfo. top or htop command.
The best way to check the number of CPU cores in Linux is by looking at the /proc/cpuinfo file. Open the terminal and run this command: cat /proc/cpuinfo | grep “cpu cores” | uniq |sed -n 1p |awk '{print $4}'. It will list the number of CPU cores on your system.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With