Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
-module(bench).
-compile(export_all).
%% Luke Gorrie's favourite profiling macro.
-define(TIME(Tag, Expr),
(fun() ->
%% NOTE: timer:tc/4 does an annoying 'catch' so we
%% need to wrap the result in 'ok' to be able to
%% detect an unhandled exception.
{__TIME, __RESULT} =
timer:tc(erlang, apply, [fun() -> {ok, Expr} end, []]),
io:format("time(~s): ~18.3fms ~999p~n",
[?MODULE, __TIME/1000, Tag]),
case __RESULT of
{ok, _} -> element(2, __RESULT);
{'EXIT', Error} -> exit(Error)
end
end)()).
-define(ITERATIONS, 10000).
-define(WORDS, 1250). %10 KB
bench() ->
?TIME(disk_log,
loop(fun disk_log_open/1, fun disk_log_write/2, fun disk_log_close/1)),
?TIME(file,
loop(fun file_open/1, fun file_write/2, fun file_close/1)),
?TIME(disk_log_sync,
loop(fun disk_log_open/1, fun disk_log_swrite/2, fun disk_log_close/1)),
?TIME(file_sync,
loop(fun file_open/1, fun file_swrite/2, fun file_close/1)).
disk_log_open(File) -> disk_log:open(disk_log_opts(File)).
disk_log_write(Log, T) -> ok = disk_log:blog(Log, term_to_binary(T)).
disk_log_swrite(Log, T) -> disk_log_write(Log, T), ok = disk_log:sync(Log).
disk_log_close(Log) -> disk_log:close(Log).
disk_log_opts(File) ->
[ {name, list_to_atom(File)}
, {file, File}
, {type, halt}
, {format, internal}
, {mode, read_write}
].
file_open(File) -> file:open(File, file_opts()).
file_write(Device, T) -> ok = file:write(Device, term_to_binary(T)).
file_swrite(Device, T) -> file_write(Device, T), ok = file:sync(Device).
file_close(Device) -> file:close(Device).
file_opts() ->
[ append
, raw
].
loop(Open, Write, Close) ->
File = file(),
false = filelib:is_file(File),
{ok, Thing} = Open(File),
do(?ITERATIONS, fun() -> Write(Thing, term()) end),
ok = Close(Thing),
ok = file:delete(File).
file() ->
os:cmd("mktemp").
term() ->
list_to_tuple([random:uniform(?ITERATIONS) || _ <- lists:seq(1, ?WORDS - 2)]).
do(0, _) -> ok;
do(N, F) -> F(), do(N-1, F).
%%% Local Variables:
%%% erlang-indent-level: 2
%%% End:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.