Detect number of CPUs installed

前端 未结 12 880
孤城傲影
孤城傲影 2020-12-24 05:29

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

相关标签:
12条回答
  • 2020-12-24 06:16

    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
    
    0 讨论(0)
  • 2020-12-24 06:16

    @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

    0 讨论(0)
  • 2020-12-24 06:17

    on Mac:

    thiago-pradis-macbook:~ tchandy$ hwprefs cpu_count

    2

    0 讨论(0)
  • 2020-12-24 06:18

    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
    
    0 讨论(0)
  • 2020-12-24 06:18

    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
    
    0 讨论(0)
  • 2020-12-24 06:21

    with JRuby you can check it with the following Java code:

     Runtime runtime = Runtime.getRuntime();   
     int numberOfProcessors = runtime.availableProcessors(); 
    
    0 讨论(0)
提交回复
热议问题