Skip to content

Instantly share code, notes, and snippets.

@zacid
Created February 25, 2017 12:47
Show Gist options
  • Save zacid/e5ffc76d54460c0a78095d5858fb638c to your computer and use it in GitHub Desktop.
Save zacid/e5ffc76d54460c0a78095d5858fb638c to your computer and use it in GitHub Desktop.
Comparison between parallel map in Elixir and map
# p_map is a parallel map which runs each and every process concurrently
> p_map = fn -> 1..5 |> Enum.map(fn(i) -> Task.async(fn -> :timer.sleep(200); i + 1 end) end) |> Enum.map(fn(tsk) -> Task.await(tsk) end) end
# slow_map runs each and every iteration one after the other
> slow_map = fn -> 1..5 |> Enum.map(fn(i) -> :timer.sleep(200); i + 1 end) end
> :timer.tc(fn -> p_map.() end, [])
{200830, [2, 3, 4, 5, 6]}
> :timer.tc(fn -> slow_map.() end, [])
{1004430, [2, 3, 4, 5, 6]}
# all results are displayed in microseconds so therefore the p_map has taken around 0.2 seconds and slow_map has taken 1 second
# each task slept 200 milliseconds which makes sense that pmap would take 0.2 seconds as each task ran in parallel
# this also explains why slow_map has taken 1 second. 200 milliseconds * 5 = 1 second to run each iteration sequentially
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment