Last active
December 20, 2015 17:09
-
-
Save nsmaciej/6166954 to your computer and use it in GitHub Desktop.
100 (and more) doors in ruby using threading.
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
Size = ARGV.first.to_i | |
doors = Array.new(Size, false) | |
(1..Size).each do |pass| | |
(0...Size).each do |pos| | |
doors[pos] = !doors[pos] if (pos+1) % pass == 0 | |
end | |
end | |
doors.each_with_index {|val, pos| puts pos+1 if val} |
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
Size = ARGV.first.to_i | |
Cpus = 4 | |
raise "Devision error" if Size % Cpus != 0 | |
Cpu_share = Size / Cpus | |
doors = Array.new(Size, false) | |
threads = [] | |
Cpus.times do |cpu| | |
threads << Thread.new(Cpu_share*cpu) do |start| | |
(1..Cpu_share).each do |pass| | |
pass += start | |
(0...Size).each do |pos| | |
doors[pos] = !doors[pos] if (pos + 1) % pass == 0 | |
end | |
end | |
end | |
end | |
threads.each {|thr| thr.join} | |
doors.each_with_index {|val, pos| puts pos+1 if val} |
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
#!/bin/bash | |
NUM=$1 | |
NONE='\033[00m' | |
BOLD='\033[01m' | |
RED='\033[01;31m' | |
GREEN='\033[01;32m' | |
TIME="/usr/bin/time -f 'Run time: %E, CPU usage: %P, Max memory: %MKb'" | |
toilet -f future $NUM | |
echo -e "${GREEN}Single thread$NONE" | |
echo -e "${BOLD}Ruby$NONE" | |
eval $TIME ruby lockers.rb $NUM | |
echo -e "${BOLD}jRuby$NONE" | |
eval $TIME jruby lockers.rb $NUM | |
echo -e "${GREEN}Multi thread (Limit thread number)$NONE" | |
echo -e "${BOLD}Ruby$NONE" | |
eval $TIME ruby lockers3.rb $NUM | |
echo -e "${BOLD}jRuby$NONE" | |
eval $TIME jruby lockers3.rb $NUM | |
echo -e "${RED}Finished$NONE" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment