Skip to content

Instantly share code, notes, and snippets.

@parroty
Created December 15, 2013 08:00
Show Gist options
  • Save parroty/7970215 to your computer and use it in GitHub Desktop.
Save parroty/7970215 to your computer and use it in GitHub Desktop.
Parallel map using future
defmodule SampleFuture do
require Future
def fib(0), do: 0
def fib(1), do: 1
def fib(n), do: fib(n - 1) + fib(n - 2)
defmacro benchmark([do: content]) do
quote do
s = :erlang.now
unquote(content)
e = :erlang.now
IO.inspect :timer.now_diff(e, s) / (1000 * 1000)
end
end
def parallel_map(collection) do
collection
|> Enum.map(Future.new(&fib/1))
|> Enum.map(&Future.value(&1))
end
def normal_map(collection) do
collection
|> Enum.map(&fib/1)
end
def run do
collection = [35, 36, 37, 38]
benchmark do
IO.inspect parallel_map(collection)
end
benchmark do
IO.inspect normal_map(collection)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment