Packages

Easily time execution of a block or function!

Current section

Files

Jump to
pocket_watch src pocket_watch.erl
Raw

src/pocket_watch.erl

-module(pocket_watch).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/pocket_watch.gleam").
-export([callback_ns/2, callback/2, simple/2, summary_simple/4]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
-file("src/pocket_watch.gleam", 58).
?DOC(
" Log time taken using a provided callback that takes `Float` nanoseconds as argument.\n"
"\n"
" ## Examples:\n"
" ```gleam\n"
" let print_time = fn(label, elapsed) {\n"
" io.println_error(label <> \" took \" <> float.to_string(elapsed /. 1_000_000.0) <> \"ms\")\n"
" }\n"
"\n"
" {\n"
" use <- pocket_watch.callback(print_time(\"test\", _))\n"
"\n"
" process.sleep(1000)\n"
" } // test took 1000.0ms\n"
" ```\n"
).
-spec callback_ns(fun((float()) -> any()), fun(() -> EFL)) -> EFL.
callback_ns(Callback, Body) ->
{Return, Ns} = pocket_watch_ffi:elapsed(Body),
Callback(Ns),
Return.
-file("src/pocket_watch.gleam", 38).
?DOC(
" Log time taken using a provided callback.\n"
"\n"
" ## Examples:\n"
" ```gleam\n"
" let print_time = fn(label, elapsed) { io.println_error(label <> \" took \" <> elapsed) }\n"
"\n"
" {\n"
" use <- pocket_watch.callback(print_time(\"test\", _))\n"
"\n"
" process.sleep(1000)\n"
" } // test took 1.0s\n"
" ```\n"
).
-spec callback(fun((binary()) -> any()), fun(() -> EFJ)) -> EFJ.
callback(Callback, Body) ->
Callback@1 = fun(Elapsed) ->
Callback(humanise:nanoseconds_float(Elapsed))
end,
callback_ns(Callback@1, Body).
-file("src/pocket_watch.gleam", 18).
?DOC(
" Log time taken using a default callback with `io.println_error`.\n"
"\n"
" ## Examples:\n"
" ```gleam\n"
" {\n"
" use <- pocket_watch.simple(\"test\")\n"
"\n"
" process.sleep(1000)\n"
" } // pocket_watch [test]: took 1.0s\n"
" ```\n"
).
-spec simple(binary(), fun(() -> EFH)) -> EFH.
simple(Label, Body) ->
Fun = fun(Elapsed) ->
gleam_stdlib:println_error(
<<<<<<"pocket_watch ["/utf8, Label/binary>>/binary,
"]: took "/utf8>>/binary,
Elapsed/binary>>
)
end,
callback(Fun, Body).
-file("src/pocket_watch.gleam", 72).
?DOC(
" > **Note**: Be aware of side effects when using any of the summary functions.\n"
" > `body` will be called multiple times and any side effects will be triggered each time.\n"
" \n"
" Shortcut to the [`simple`](./pocket_watch/summary.html#simple) function in the [`summary`](./pocket_watch/summary.html) module.\n"
"\n"
" Check out that function for details!\n"
).
-spec summary_simple(binary(), integer(), integer(), fun(() -> EFM)) -> EFM.
summary_simple(Label, N, Warmup, Body) ->
pocket_watch@summary:simple(Label, N, Warmup, Body).