ruby - 检测 IDLE 处理器 ruby​​ 的数量

标签 ruby linux unix shell

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

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

(也许有一种纯 ruby​​ 的方式来做到这一点?)

但有时同事会使用 24 个内核中的 6 个或 8 个。 (如顶部所示)。我如何才能估算出我可以使用的当前未使用处理器的数量而不会让任何人感到不安?

谢谢!

最佳答案

您可以使用 /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)

关于ruby - 检测 IDLE 处理器 ruby​​ 的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2624391/

相关文章:

ruby - 无法通过测试单元( ruby )传递 ARGV

Ruby反射问题

arrays - 使用 du 定义遍历目录的数组

linux - UNIX如何多次解析目录中的文件列表

linux - 希望 sed 有一个与 ed 方便的 j 命令等效的命令

c - 传输端点未连接 recv 套接字

ruby - 将数组拆分为(元素=>剩余元素)对的方法

ruby-on-rails - Rspec 期望(实例)接收方法未按预期工作

linux - 无法在 Ubuntu 上运行我自己的 OpenGL 3 程序

python - 如何修改zabbix脚本?