Created
October 11, 2013 09:06
-
-
Save yannickwurm/6931821 to your computer and use it in GitHub Desktop.
Detecting numbers of processors in ruby (old ugly code)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def YWSystemTools.number_of_processors | |
if RUBY_PLATFORM =~ /linux/ | |
cpuinfo = IO.readlines("/proc/cpuinfo").delete_if{|x| x.index("processor")==nil} | |
return cpuinfo.length | |
elsif RUBY_PLATFORM =~ /darwin/ | |
return `sysctl -n hw.logicalcpu`.to_i | |
elsif RUBY_PLATFORM =~ /win32/ | |
# this works for windows 2000 or greater | |
require 'win32ole' | |
wmi = WIN32OLE.connect("winmgmts://") | |
wmi.ExecQuery("select * from Win32_ComputerSystem").each do |system| | |
begin | |
processors = system.NumberOfLogicalProcessors | |
rescue | |
processors = 0 | |
end | |
return [system.NumberOfProcessors, processors].max | |
end | |
end | |
raise "can't determine 'number_of_processors' for '#{RUBY_PLATFORM}'" | |
end | |
private | |
def YWSystemTools.numberOfActiveProcessors # internal | |
processorForProcs = [] | |
processFiles = Dir.glob("/proc/*/stat") | |
raise IOError, 'Cannot find /proc/*/stat files. Are you sure this is a linux machine?' if processFiles.empty? | |
processFiles.each do |filename| | |
next if File.directory?(filename) # because /proc/net/stat is a directory | |
next if !File.exists?(filename) # may have disappeared in the meantime | |
this_proc = [] | |
File.open(filename) { |file| this_proc = file.gets.split.values_at(2,38) } | |
processorForProcs << this_proc[1].to_i if this_proc[0]=="R" | |
end | |
processorsInUse = processorForProcs.uniq | |
return(processorsInUse.length) | |
end | |
public | |
def YWSystemTools.numberOfAvailableProcessors | |
numberOfAttempts = 5 | |
$log.info("Will determine number of available processors. Wait #{numberOfAttempts.to_s} seconds.") | |
#we estimate 5 times because of local fluctuations in procesor use. Keep minimum. | |
estimationsOfNumberOfActiveProcessors = [] | |
numberOfAttempts.times do | |
estimationsOfNumberOfActiveProcessors << YWSystemTools.numberOfActiveProcessors | |
sleep(1) | |
end | |
numberOfActiveProcessors = estimationsOfNumberOfActiveProcessors.min | |
numberOfTotalProcessors = number_of_processors() | |
raise IOError, '!! # active Processors > # processors' if numberOfActiveProcessors > numberOfTotalProcessors | |
numberOfAvailableProcessors = numberOfTotalProcessors - numberOfActiveProcessors | |
$log.info("#{numberOfAvailableProcessors} out of #{numberOfTotalProcessors} are available!") | |
return(numberOfAvailableProcessors) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment