我已经通过cat /proc/cpuinfo找到了"大多数Unix"的解决方案,但纯Ruby解决方案会更好.

推荐答案

我目前正在使用它,它涵盖了所有操作系统.

  def self.processor_count
    case RbConfig::CONFIG['host_os']
    when /darwin9/
      `hwprefs cpu_count`.to_i
    when /darwin/
      ((`which hwprefs` != '') ? `hwprefs thread_count` : `sysctl -n hw.ncpu`).to_i
    when /linux/
      `cat /proc/cpuinfo | grep processor | wc -l`.to_i
    when /freebsd/
      `sysctl -n hw.ncpu`.to_i
    when /mswin|mingw/
      require 'win32ole'
      wmi = WIN32OLE.connect("winmgmts://")
      cpu = wmi.ExecQuery("select NumberOfCores from Win32_Processor") # TODO count hyper-threaded in this
      cpu.to_enum.first.NumberOfCores
    end
  end

Ruby相关问答推荐

在Glade创建的UI中以编程方式填充GtkTreeView

MongoDB通过Brew Services";未定义的方法`plist_starting';";

Ruby - 使用索引值识别和更新数组中的重复项

根据部分已知值判断数组内容的简洁 Rubyist 方法是什么?

Ruby:一个方法可以返回不同类型的对象吗?

整数除以负数

是否应该在生产时缩小服务器代码?

为什么 Rake 不能连续调用多个任务?

Ruby 中的字符串是可变的吗?

Encoding::UndefinedConversionError

Ruby - 将块传递给方法

如何判断是否安装了gem?

Ruby字符串上的扫描和匹配有什么区别

无法正确自动生成 Ruby DevKit 配置文件

Ruby 2 中的命名参数

如何通过拆分字符的最后一次出现将字符串拆分为仅两部分?

在 Ruby 中, coerce() 是如何工作的?

在类方法中使用实例变量 - Ruby

Ruby 中的Monkey Patching到底是什么意思?

在 Ruby 中使用元组?