public
Last active

list and binary copy benchmark in Erlang

  • Download Gist
Makefile
Makefile
1 2 3 4 5
test: t.beam
erl -eval 't:bench(), init:stop()'
 
t.beam: t.erl
erlc -smp +native $<
t.erl
Erlang
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
-module(t).
 
-export([bench/0, test_bin_copy/1, test_string_copy/1]).
 
bench() ->
bench(1 bsl 20, 30).
 
bench(N, Rep) ->
Self = self(),
io:format("Creating str of size ~p.. ", [N]),
L = [X rem 255 || X <- lists:seq(1, N)],
io:format("done.~n"),
io:format("Converting to binary.. "),
B = iolist_to_binary(L),
io:format("done.~n"),
 
io:format("Executing PREFILL BIN copy ~p times... ", [Rep]),
spawn_link(fun() -> bench_str(B, Rep, Self) end),
_TimesBinX = receive {bin, A2} -> A2 end,
io:format("done.~n"),
timer:sleep(100),
io:format("Executing PREFILL STR copy ~p times... ", [Rep]),
spawn_link(fun() -> bench_bin(L, Rep, Self) end),
_TimesStr = receive {str, A0} -> A0 end,
io:format("done.~n"),
timer:sleep(100),
 
io:format("Executing STR copy ~p times... ", [Rep]),
spawn_link(fun() -> bench_bin(L, Rep, Self) end),
TimesStr = receive {str, A1} -> A1 end,
io:format("done.~n"),
timer:sleep(100),
 
io:format("Executing BIN copy ~p times... ", [Rep]),
spawn_link(fun() -> bench_str(B, Rep, Self) end),
TimesBin = receive {bin, A3} -> A3 end,
io:format("done.~n"),
timer:sleep(100),
 
MeanBin = lists:sum(TimesBin) / Rep,
MeanStr = lists:sum(TimesStr) / Rep,
StdBin = std_dev(TimesBin, MeanBin),
StdStr = std_dev(TimesStr, MeanStr),
io:format("BIN: Min: ~9.1f, Max: ~9.1f, Mean: ~9.1f, stdev: ~8.1f~n",
[float(lists:min(TimesBin)), float(lists:max(TimesBin)),
MeanBin, StdBin]),
io:format("STR: Min: ~9.1f, Max: ~9.1f, Mean: ~9.1f, stdev: ~8.1f~n",
[float(lists:min(TimesStr)), float(lists:max(TimesStr)),
MeanStr, StdStr]).
 
bench_bin(L, Rep, Pid) ->
TimesStr = [
begin
{T, _} = timer:tc(fun() -> test_string_copy(L) end),
T
end || _ <- lists:seq(1, Rep)
],
Pid ! {str, TimesStr}.
 
bench_str(B, Rep, Pid) ->
TimesBin = [
begin
{T, _} = timer:tc(fun() -> test_bin_copy(B) end),
T
end || _ <- lists:seq(1, Rep)
],
Pid ! {bin, TimesBin}.
 
 
test_bin_copy(Bin) ->
test_bin_copy(Bin, <<>>).
test_bin_copy(<<>>, Accum) ->
Accum;
test_bin_copy(<<Char, Rest/binary>>, Accum) ->
test_bin_copy(Rest, <<Accum/binary, Char>>).
 
test_string_copy(Bin) ->
test_string_copy(Bin, []).
test_string_copy([], Accum) ->
lists:reverse(Accum);
test_string_copy([Char|Rest], Accum) ->
test_string_copy(Rest, [Char|Accum]).
 
std_dev(Values, Avg) ->
Sums = lists:foldl(
fun(V, Acc) -> D = V - Avg, Acc + (D * D) end,
0, Values),
math:sqrt(Sums / (length(Values) - 1)).

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.