Skip to content

Instantly share code, notes, and snippets.

@egobrain
Created January 26, 2015 12:59
Show Gist options
  • Save egobrain/986e66b0f6adad687396 to your computer and use it in GitHub Desktop.
Save egobrain/986e66b0f6adad687396 to your computer and use it in GitHub Desktop.
Maps performace (update by key) test.
-module(t).
-compile(export_all).
-record(r, {a1,a2,a3,a4,a5,a6,a7,a8}).
test(F, N, Times) ->
NSeq = lists:seq(1, N),
TimeSeq = lists:seq(1, Times),
R =
[
element(1, timer:tc(fun() -> [F() || _ <- NSeq] end))
|| _ <- TimeSeq
],
#{
min => lists:min(R),
max => lists:max(R),
avg => lists:sum(R)/(N*Times)
}.
p_test(F, N, Threads) ->
NSeq = lists:seq(1, N),
ThreadsSeq = lists:seq(1, Threads),
Self = self(),
Ref = make_ref(),
lists:foreach(
fun(_) ->
spawn(
fun() ->
T = element(1, timer:tc(fun() -> [F() || _ <- NSeq] end)),
Self ! {Ref, T}
end)
end, ThreadsSeq),
R = [receive {Ref, T} -> T end|| _ <- ThreadsSeq],
#{
min => lists:min(R),
max => lists:max(R),
avg => lists:sum(R)/(N*Threads)
}.
test() ->
N = 10000,
Times = 1000,
Test = fun(A) -> test(A, N, Times) end,
Threads = 1000,
PTest = fun(A) -> p_test(A, N, Threads) end,
[
{seq, test(Test)},
{par, test(PTest)}
].
test(T) ->
Tuple = {1,2,3,4,5,6,7,8},
Map = #{a1 => 1, a2 => 2, a3 => 3, a4 => 4, a5 => 5, a6 => 6, a7 => 7, a8 => 8},
List = [{a1, 1}, {a2 , 2}, {a3 , 3}, {a4 , 4}, {a5 , 5}, {a6 , 6}, {a7 , 7}, {a8 , 8}],
Record = #r{a1=1, a2=2, a3=3, a4=4, a5=5, a6=6, a7=7, a8=8},
I = a8,
V = a,
[
{tuple, T(fun() -> setelement(8, Tuple, V) end)}, %% Hardcoded index
{record, T(fun() -> Record#r{a8=V} end)}, %% Hardcoded index
{map1, T(fun() -> Map#{a8 => V} end)}, %% Hardcoded index
{map2, T(fun() -> maps:update(I, V, Map) end)},
{list, T(fun() -> lists:keystore(I, 1, List, {I, V}) end)}
].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment