Skip to content

Instantly share code, notes, and snippets.

Created September 13, 2010 17:15
Show Gist options
  • Save anonymous/577656 to your computer and use it in GitHub Desktop.
Save anonymous/577656 to your computer and use it in GitHub Desktop.
-module(bm_ets).
-export([run/0]).
run() ->
io:format("Testing List~n"),
List = fill_list(),
perftest(1000, fun() -> run_list(List) end),
io:format("Testing ETS~n"),
ETS = fill_ets(),
perftest(1000, fun() -> run_ets(ETS) end),
ok.
repeat(0,_F) -> ok;
repeat(N, F) -> F(), repeat(N-1, F).
perftest(N, F) -> perftest("Sequential", N, F).
perftest(Name, Cycles, F) ->
{_, StartSecs, StartMS} = now(),
repeat(Cycles, F),
{_, StopSecs, StopMS} = now(),
MS = (StopSecs * 1000 + StopMS / 1000)
- (StartSecs * 1000 + StartMS / 1000),
CPS = round(1000 * Cycles / MS),
io:format("~s ~p cycles in ~~~p seconds (~p cycles/s)~n",
[Name, Cycles, round(MS / 1000), CPS]),
CPS.
fill_list() ->
[{Num, random_state(), make_ref()} || Num <- lists:seq(1,5000)].
fill_ets() ->
Ts = ets:new(bm_ets, [set, private]),
Td = ets:new(bm_ets, [duplicate_bag, {keypos, 2}, private]),
[ets:insert(T, Entry) || T <- [Ts, Td], Entry <- fill_list()],
{Ts, Td}.
random_state() ->
Rand = random:uniform(100),
if
Rand > 67 -> active;
Rand > 33 -> starting;
true -> paused
end.
run_ets({Ts, Td}) ->
State = active,
List = ets:lookup(Td, State),
Num = random:uniform(5000),
[OldObject] = ets:lookup(Ts, Num),
{Num, _OldState, OldRef} = OldObject,
NewState = random_state(),
ets:update_element(Ts, Num, {2, NewState}),
ets:delete_object(Td, OldObject),
ets:insert(Td, {Num, NewState, OldRef}),
List.
run_list(Clients) ->
State = active,
% If L is unused, compiler will throw away [...] computation.
L = [Pid || {_Id, S, Pid} <- Clients, S == State],
Key = random:uniform(5000),
Clients1 = case lists:keyfind(Key, 1, Clients) of
false -> Clients;
Tuple -> lists:keystore(Key, 1, Clients,
setelement(2, Tuple, random_state()))
end,
{L, Clients1}.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment