Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect number of CPUs installed

Tags:

ruby

I already found a solution for "Most unixes" via cat /proc/cpuinfo, but a pure-Ruby solution would be nicer.

like image 779
grosser Avatar asked May 21 '09 05:05

grosser


People also ask

How do I check how many CPUs I have?

Press Ctrl + Shift + Esc to open Task Manager. Select the Performance tab to see how many cores and logical processors your PC has.

How many CPUs do I have command-line?

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.

How do I find the number of CPUs in Linux?

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.


2 Answers

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 
like image 178
Brandon Anzaldi Avatar answered Sep 19 '22 05:09

Brandon Anzaldi


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.

like image 34
Anko Avatar answered Sep 19 '22 05:09

Anko