Last active
November 21, 2022 13:55
-
-
Save cr0t/33a6a6035adf4ec87554eeded2e31f2b to your computer and use it in GitHub Desktop.
Performance comparison between simple `Enum.map` and `Task.async_stream` in Elixir (oversimplified case)
This file contains hidden or 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
Mix.install([ | |
{:benchee, "~> 1.0"} | |
]) | |
defmodule Cruncher do | |
def async(n) do | |
1..n | |
|> Task.async_stream(&(&1 ** 2)) | |
|> Enum.reduce(0, fn {:ok, s}, acc -> s + acc end) | |
end | |
def map(n) do | |
1..n | |
|> Enum.map(&Integer.pow(&1, 2)) | |
|> Enum.sum() | |
end | |
end | |
Benchee.run(%{ | |
"async" => fn -> Cruncher.async(1000) end, | |
"map" => fn -> Cruncher.map(1000) end | |
}) | |
# Example run: | |
# | |
# Operating System: macOS | |
# CPU Information: Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz | |
# Number of Available Cores: 12 | |
# Available memory: 32 GB | |
# Elixir 1.14.1 | |
# Erlang 25.1.2 | |
# | |
# Benchmark suite executing with the following configuration: | |
# warmup: 2 s | |
# time: 5 s | |
# memory time: 0 ns | |
# reduction time: 0 ns | |
# parallel: 1 | |
# inputs: none specified | |
# Estimated total run time: 14 s | |
# | |
# Benchmarking async ... | |
# Benchmarking map ... | |
# | |
# Name ips average deviation median 99th % | |
# map 38.01 K 0.0263 ms ±31.32% 0.0248 ms 0.0504 ms | |
# async 0.161 K 6.21 ms ±7.40% 6.10 ms 8.25 ms | |
# | |
# Comparison: | |
# map 38.01 K | |
# async 0.161 K - 235.99x slower +6.18 ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment