Skip to content

Instantly share code, notes, and snippets.

@xlymian
Created March 7, 2010 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xlymian/324599 to your computer and use it in GitHub Desktop.
Save xlymian/324599 to your computer and use it in GitHub Desktop.
require 'benchmark'
require 'matrix'
class Array
def parallel_map(&block)
result = []
# Creating a group to synchronize block execution.
group = Dispatch::Group.new
# We will access the `result` array from within this serial queue,
# as without a GIL we cannot assume array access to be thread-safe.
result_queue = Dispatch::Queue.new('access-queue.#{result.object_id}')
0.upto(size) do |idx|
# Dispatch a task to the default concurrent queue.
Dispatch::Queue.concurrent.async(group) do
temp = block[self[idx]]
puts temps
result_queue.async(group) { result[idx] = temp }
end
end
# Wait for all the blocks to finish.
group.wait
result
end
end
FIB_MATRIX = Matrix[[1,1],[1,0]]
def fib(n)
(FIB_MATRIX**(n-1))[0,0]
end
N = 100000
M = 32
ARR = (0..M).to_a
T = 50
Benchmark.bm do |b|
b.report(">> ") do
T.times { ARR.map{ fib N } }
end
b.report("++ ") do
T.times { ARR.parallel_map{ fib N } }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment