-
-
Save mariusbutuc/f9c0783827d357a4a5ed45fee18f61e6 to your computer and use it in GitHub Desktop.
Comparison between parallel map in Elixir and map
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
# 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