微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

检测空闲处理器ruby的数量

我在4到24个内核之间的共享linux计算机上工作.为了充分利用它们,我使用以下代码从我的ruby脚本中检测处理器的数量

return `cat /proc/cpuinfo | grep processor | wc -l`.to_i

(也许有一种纯ruby的方法?)

但是有时候,一个同事正在使用24个核心中的六个或八个. (如顶部所示).我如何才能估计可使用的当前未使用处理器的数量,而不会令任何人烦恼?

谢谢!

解决方法:

您可以使用/ proc文件系统中的数据来获取正在运行的进程的cpu关联性信息.以下应该为您提供当前正在使用的cpu数量(注意:我没有Linux或Ruby盒,因此该代码未经测试,但是您可以理解):

def processors_in_use
    procs=[]
    Dir.glob("/proc/*/stat") {|filename|
        next if File.directory?(filename)
        this_proc=[]
        File.open(filename) {|file| this_proc = file.gets.split.values_at(2,38)}
        procs << this_proc[1].to_i if this_proc[0]=="R"
    }
    procs.uniq.length
end

def num_processors
    IO.readlines("/proc/cpuinfo").delete_if{|x| x.index("processor")==nil}.length
end

def num_free_processors
    num_processors - processors_in_use
end

def estimate_free_cpus(count, waittime)
    results=[]
    count.times {
        results << num_free_processors
        sleep(waittime)
    }
    sum=0
    results.each {|x| sum += x}
    (sum.to_f / results.length).round
end

编辑:我验证了上面的代码工作(我正在使用Ruby 1.9)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐