Method: Autobuild.autodetect_processor_count

Defined in:
lib/autobuild/subprocess.rb

.autodetect_processor_countObject

Returns the number of CPUs present on this system



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/autobuild/subprocess.rb', line 77

def self.autodetect_processor_count
    return @processor_count if @processor_count

    if File.file?('/proc/cpuinfo')
        cpuinfo = File.readlines('/proc/cpuinfo')
        physical_ids  = []
        core_count    = []
        processor_ids = []
        cpuinfo.each do |line|
            case line
            when /^processor\s+:\s+(\d+)$/
                processor_ids << Integer($1)
            when /^physical id\s+:\s+(\d+)$/
                physical_ids << Integer($1)
            when /^cpu cores\s+:\s+(\d+)$/
                core_count << Integer($1)
            end
        end

        # Try to count the number of physical cores, not the number of
        # logical ones. If the info is not available, fallback to the
        # logical count
        has_consistent_info =
            (physical_ids.size == core_count.size) &&
            (physical_ids.size == processor_ids.size)
        if has_consistent_info
            info = Array.new
            while (id = physical_ids.shift)
                info[id] = core_count.shift
            end
            @processor_count = info.compact.inject(&:+)
        else
            @processor_count = processor_ids.size
        end
    else
        result = Open3.popen3("sysctl", "-n", "hw.ncpu") do |_, io, _|
            io.read
        end
        @processor_count = Integer(result.chomp.strip) unless result.empty?
    end

    # The format of the cpuinfo file is ... let's say not very standardized.
    # If the cpuinfo detection fails, inform the user and set it to 1
    unless @processor_count
        # Hug... What kind of system is it ?
        Autobuild.message "INFO: cannot autodetect the number of CPUs on this sytem"
        Autobuild.message "INFO: turning parallel builds off"
        Autobuild.message "INFO: you can manually set the number of parallel build "\
            "processes to N"
        Autobuild.message "INFO: (and therefore turn this message off)"
        Autobuild.message "INFO: with"
        Autobuild.message "    Autobuild.parallel_build_level = N"
        @processor_count = 1
    end

    @processor_count
end