Skip to content

Instantly share code, notes, and snippets.

@andytill
Forked from 0xYUANTI/bench.erl
Last active August 29, 2015 13:56
Show Gist options
  • Save andytill/9261270 to your computer and use it in GitHub Desktop.
Save andytill/9261270 to your computer and use it in GitHub Desktop.
-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) ->
MaxFiles = 5,
MaxFileSize = 1,
[ {name, list_to_atom(File)}
, {file, File}
, {type, wrap}
, {size, {MaxFileSize * 1024 * 1024, MaxFiles}}
, {format, external}
, {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
, delayed_write
].
loop(Open, Write, Close) ->
File = file(),
false = filelib:is_file(File),
{ok, Thing} = Open(File),
T = term(),
do(?ITERATIONS, fun() -> Write(Thing, T) 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:
@andytill
Copy link
Author

Added delay_write for files, this edges file writing over disk_log, but only just!

@andytill
Copy link
Author

Note that disk_log:blog also supports IO lists.

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