Created
August 8, 2008 08:21
-
-
Save eric/4552 to your computer and use it in GitHub Desktop.
Parallel map: Originally from http://project.ioni.st/post/2332#snippet_2332
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
# Parallel map | |
# Originally from http://project.ioni.st/post/2332#snippet_2332 | |
class Array | |
def pmap | |
threads = [] | |
0.upto(size - 1) do |n| | |
threads << Thread.new do | |
yield(at(n)) | |
end | |
end | |
threads.collect {|thread| thread.value} | |
end | |
end | |
# Trade-off between resource consumption | |
# and speed of execution. | |
# Much faster in some scenarios, | |
# much slower in others. | |
# e.g. | |
def expensive_operation | |
open('http://google.com').read | |
end | |
# Expensive operation 50 times | |
# user system total real | |
# map 50x 0.3400 0.2100 0.5500 ( 17.334429) | |
# pmap 50x 0.3000 0.2500 0.5500 ( 1.200705) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment