Skip to content

Instantly share code, notes, and snippets.

@amutake
Created June 15, 2018 12:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amutake/d3700996030a5d4237c55f2f289a0c39 to your computer and use it in GitHub Desktop.
Save amutake/d3700996030a5d4237c55f2f289a0c39 to your computer and use it in GitHub Desktop.
Erlang のメッセージパッシングのコストに関する雑なベンチマーク
-module(fun_call_vs_msg_passing_heavy).
-export([fun_call/1, msg_passing/1]).
fib(0) -> 0;
fib(1) -> 1;
fib(N) -> fib(N - 1) + fib(N - 2).
%% fib(20) (そこそこ重い処理のつもり) を N 回呼び出す
fun_call(N) ->
timer:tc(fun () -> lists:foreach(fun (_) -> fib(20) end, lists:seq(0, N)) end).
%% fib(20) の処理を別プロセスやってもらい, 結果を返してもらう. というのを N 回行う.
msg_passing(N) ->
Worker = spawn_link(fun Loop() -> receive {_, Sender} -> Sender ! fib(20) end, Loop() end),
Self = self(),
timer:tc(fun () -> lists:foreach(fun (X) -> Worker ! {X, Self}, receive Y -> Y end end, lists:seq(0, N)) end).
-module(fun_call_vs_msg_passing_light).
-export([fun_call/1, msg_passing/1]).
id(X) -> X.
%% id 関数を N 回呼び出す
fun_call(N) ->
timer:tc(fun () -> lists:foreach(fun (X) -> id(X) end, lists:seq(0, N)) end).
%% id 関数の呼び出しを別プロセスにやってもらい, 結果を返してもらう. というのを N 回行う.
msg_passing(N) ->
Worker = spawn_link(fun Loop() -> receive {X, Sender} -> Sender ! id(X) end, Loop() end),
Self = self(),
timer:tc(fun () -> lists:foreach(fun (X) -> Worker ! {X, Self}, receive Y -> Y end end, lists:seq(0, N)) end).
1> c(fun_call_vs_msg_passing_light).
{ok,fun_call_vs_msg_passing_light}
2> fun_call_vs_msg_passing_light:fun_call(1000000).
{44185,ok}
3> fun_call_vs_msg_passing_light:msg_passing(1000000).
{1301580,ok} <--- 軽い処理を別プロセスにメッセージパッシングでやらせると30倍くらいのコスト
1> c(fun_call_vs_msg_passing_heavy).
{ok,fun_call_vs_msg_passing_heavy}
2> fun_call_vs_msg_passing_heavy:fun_call(100000).
{37862940,ok}
3> fun_call_vs_msg_passing_heavy:msg_passing(100000).
{37378970,ok} <--- 重い処理を別プロセスにメッセージパッシングでやらせても変わらない
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment