Detect number of CPUs installed

前端 未结 12 920
孤城傲影
孤城傲影 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
    

提交回复
热议问题