Skip to content

Instantly share code, notes, and snippets.

@kocolosk
Created April 21, 2010 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kocolosk/374220 to your computer and use it in GitHub Desktop.
Save kocolosk/374220 to your computer and use it in GitHub Desktop.
-module(keysearch_microbench).
-compile(export_all).
test(ListLength, NumberOfReps) ->
crypto:start(),
Data = make_data(ListLength),
% TestId = key(), % worst-case, missing key
TestId = element(1,lists:nth(4,Data)), % some key in the list
Counter = lists:seq(1,NumberOfReps),
T0 = now(),
[get_value(TestId, Data) || _I <- Counter],
T1 = now(),
[proplists:get_value(TestId, Data) || _I <- Counter],
T2 = now(),
{timer:now_diff(T1, T0), timer:now_diff(T2, T1)}.
% proplists:get_value API wrapper around keysearch
get_value(Key, List) ->
get_value(Key, List, undefined).
get_value(Key, List, Default) ->
case lists:keysearch(Key, 1, List) of
{value, {Key,Value}} ->
Value;
false ->
Default
end.
make_data(0) ->
[];
make_data(N) ->
[{key(), random:uniform()}|make_data(N-1)].
key() ->
list_to_binary(to_hex(crypto:rand_bytes(16))).
to_hex([]) ->
[];
to_hex(Bin) when is_binary(Bin) ->
to_hex(binary_to_list(Bin));
to_hex([H|T]) ->
[to_digit(H div 16), to_digit(H rem 16) | to_hex(T)].
to_digit(N) when N < 10 -> $0 + N;
to_digit(N) -> $a + N-10.
@KlausTrainer
Copy link

Hi Adam,

I first got an error trying to run the benchmark, before I had figured out that the crypto server needs to be started.
Consequently, I'd suggest to insert a "crypto:start()," into the first line of test/2. (In the case the crypto server is already running, it at least will not harm.)

With kind regards,
Klaus

@kocolosk
Copy link
Author

Klaus, thanks! I certainly should have added that in the beginning.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment