Created
December 15, 2013 08:00
-
-
Save parroty/7970215 to your computer and use it in GitHub Desktop.
Parallel map using future
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
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