File: cpu_counter.rb

package info (click to toggle)
ruby-celluloid 0.18.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 848 kB
  • sloc: ruby: 7,579; makefile: 10
file content (62 lines) | stat: -rw-r--r-- 1,565 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
module Celluloid
  module Internals
    module CPUCounter
      class << self
        def cores
          @cores ||= count_cores
        end

        def count_cores
          from_result(from_env || from_sysdev || from_java || from_proc || from_win32ole || from_sysctl) || 1
        end

        def from_env
          result = ENV["NUMBER_OF_PROCESSORS"]
          result if result && !result.empty?
        rescue
        end

        def from_sysdev
          ::IO.read("/sys/devices/system/cpu/present").split("-").last.to_i + 1
        rescue Errno::ENOENT
          begin
            result = Dir["/sys/devices/system/cpu/cpu*"].count { |n| n =~ /cpu\d+/ }
            result unless result.zero?
          rescue
          end
        rescue
        end

        def from_java
          Java::Java.lang.Runtime.getRuntime.availableProcessors if defined? Java::Java
        rescue
        end

        def from_proc
          File.read("/proc/cpuinfo").scan(/^processor\s*:/).size if File.exist?("/proc/cpuinfo")
        rescue
        end

        def from_win32ole
          require "win32ole"
          WIN32OLE.connect("winmgmts://").ExecQuery("select * from Win32_ComputerSystem").NumberOfProcessors
        rescue LoadError
        rescue
        end

        def from_sysctl
          Integer `sysctl -n hw.ncpu 2>/dev/null`
        rescue
        end

        def from_result(result)
          if result
            i = Integer(result.to_s[/\d+/], 10)
            return i if i > 0
          end
        rescue
        end
      end
    end
  end
end