Skip to content

Instantly share code, notes, and snippets.

@shino
Created December 15, 2015 03:22
Show Gist options
  • Save shino/94fc9029608f743a9e1b to your computer and use it in GitHub Desktop.
Save shino/94fc9029608f743a9e1b to your computer and use it in GitHub Desktop.
-module(bm).
-export([help/0, bm/2, bm/3, bmp/3]).
help() ->
io:format("bm(F, Count) -- execute microbench function F\n"),
io:format("bm(F, Count) -- execute microbench function F\n"),
io:format("bm(F, CountPerProcess, Processes) -- execute microbench function F in parallel\n"),
io:format("bmp(F, CountPerProcess, Processes) -- execute microbench function F in parallel\n"),
ok.
bm(Fun, Count) ->
spawn(fun() ->
{USec, _Value} = timer:tc(fun() -> bm0(Fun, Count) end),
bm_format(USec, Count)
end).
bm_format(USec, Count) ->
%% ?debugVal(USec),
io:nl(),
bm_format(USec, Count, both).
bm_format(USec, Count, usec) ->
io:format("total: ~B [usec] / ~B [ops]~n", [USec, Count]),
io:format("single: ~f [usec/op]~n", [USec / Count]);
bm_format(USec, Count, msec) ->
io:format("total: ~f [msec] / ~B [ops]~n", [USec / 1000, Count]),
io:format("single: ~f [msec/op]~n", [USec / 1000 / Count]);
bm_format(USec, Count, both) ->
io:format("============= [in micro seconds] =============~n"),
bm_format(USec, Count, usec),
io:format("============= [in milli seconds] =============~n"),
bm_format(USec, Count, msec),
io:format("==============================================~n").
bm(Fun, CountPerProcess, Processes) ->
bmp(Fun, CountPerProcess, Processes).
bmp(Fun, CountPerProcess, Processes) ->
spawn_link(fun() -> bmp0(Fun, CountPerProcess,Processes) end).
bmp0(Fun, CountPerProcess, Processes) ->
Self = self(),
ListOfPid = [spawn_link(fun() -> bmp_process(Self, Fun, CountPerProcess) end) ||
_ <- lists:seq(1, Processes)],
[Pid ! start || Pid <- ListOfPid],
ListOfUSec = [receive {_, USec, _Count} -> USec end || _Pid <- ListOfPid],
%% ?debugVal(ListOfUSec),
io:nl(),
io:format("============ Turn around time ================~n"),
io:format("Minimum~n"),
bm_format(lists:min(ListOfUSec), CountPerProcess, msec),
io:format("Maximum~n"),
bm_format(lists:max(ListOfUSec), CountPerProcess, msec),
TotalUSec = lists:sum(ListOfUSec),
io:format("Average~n"),
bm_format(TotalUSec div Processes, CountPerProcess, msec),
io:format("============ Throughput ======================~n"),
io:format("~f [ops/msec]~n", [CountPerProcess * Processes / (TotalUSec / Processes / 1000)]),
io:nl(),
ok.
bmp_process(From, Fun, Count) ->
receive
start ->
{USec, _Value} = timer:tc(fun() -> bm0(Fun, Count) end),
From ! {self(), USec, Count}
end.
bm0(_Fun, 0) ->
ok;
bm0(Fun, Count) ->
Fun(),
bm0(Fun, Count - 1).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment