Ank*_*nko 37
编辑:现在rails附带并发ruby作为依赖,所以它可能是最好的解决方案;
$ 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
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅http://ruby-concurrency.github.io/concurrent-ruby/root/Concurrent.html.因为它同时具有物理和逻辑核心,所以它比内置核心更好Etc.nprocessors.
这是以前的答案;
$ 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>
Run Code Online (Sandbox Code Playgroud)
如果你想要关于系统的其他事实,这个更好的宝石是最好的,它不是特定于平台的,并且旨在做到这一点.
更新:更新以包括Nathan Kleyn关于api更改的提示.
Bra*_*ldi 37
从Ruby 2.2.3版开始,etcRuby的stdlib中的模块提供了一个nprocessors返回处理器数量的方法.需要注意的是,如果将ruby降级为CPU核心的子集,Etc.nprocessors则只返回Ruby可以访问的核心数.此外,正如seanlinsley所指出的,这只会返回虚拟核心而不是物理核心,这可能会导致预期值的差异.
require 'etc'
p Etc.nprocessors #=> 4
Run Code Online (Sandbox Code Playgroud)
gro*_*ser 26
我目前正在使用它,它涵盖了所有操作系统. https://github.com/grosser/parallel/blob/master/lib/parallel.rb#L63
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
Run Code Online (Sandbox Code Playgroud)
dfa*_*dfa 11
使用JRuby,您可以使用以下Java代码进行检查:
Runtime runtime = Runtime.getRuntime();
int numberOfProcessors = runtime.availableProcessors();
Run Code Online (Sandbox Code Playgroud)
Kon*_*ase 10
以下是Linux,OSX,Windows和BSD的实现:https://gist.github.com/1009994
源代码:
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
Run Code Online (Sandbox Code Playgroud)
当然,如果可以cat,您可以使用该语言的标准功能打开,阅读和关闭它,而无需求助于system()类型调用.
您可能只需要动态检测您所在的平台,并且:
/proc/cpuinfoLinux 的"文件"; 要么最后一行可以使用:
require 'win32ole'
wmi = WIN32OLE.connect("winmgmts://")
info = wmi.ExecQuery ("select * from Win32_ComputerSystem")
Run Code Online (Sandbox Code Playgroud)
然后使用info的NumberOfProcessors项.
| 归档时间: |
|
| 查看次数: |
13424 次 |
| 最近记录: |