Performance profiling
The performance lesson names the shapes worth changing; this one is about knowing which shape a program actually has. The rule is the same in every language: measure, change one thing, measure again. In Erlang the first measurement is a call to timer:tc, the second is a count of calls, and only a program that is still slow after both deserves a profiler.
Measure a change
timer:tc(Fun) runs a fun and answers {Microseconds, Value}; timer:tc(Module, Function, Args) does the same for a remote call. The value comes back with the time, so a measurement never loses the answer. The program measures a list comprehension and a library call and prints the answers, not the microseconds:
measure.erl
-module(measure). -export([main/0]). main() -> Input = lists:seq(1, 2000), {Time, Doubled} = timer:tc(fun() -> double(Input) end), {Time2, Sum} = timer:tc(lists, sum, [Doubled]), io:format("doubled the head: ~p~n", [hd(Doubled)]), io:format("sum: ~p~n", [Sum]), io:format("two timings: ~p~n", [is_integer(Time) andalso is_integer(Time2)]). double(List) -> [N * 2 || N <- List].
erlc measure.erl
erl -noshell -eval 'measure:main(), halt().'
doubled the head: 2 sum: 4002000 two timings: true
A single run is not a measurement: the first call pays for code loading and the garbage collector runs when it likes. Run the fun a thousand times and divide, or run the whole program five times and compare the spread. The page prints the answers and their correctness, because the microseconds of this machine would be someone else's milliseconds on another one.
Count the calls
A function that runs a million times is usually the problem, and the count does not depend on the speed of the machine. erlang:trace/3 and erlang:trace_pattern/3 are the two calls every counter is built on. The program traces one worker and counts the calls of a recursive function in the tracer's own mailbox:
count_calls.erl
-module(count_calls). -export([main/0, work/1]). main() -> Self = self(), Pid = spawn(fun() -> receive go -> ok end, Self ! {done, work(5)} end), 1 = erlang:trace(Pid, true, [call]), 1 = erlang:trace_pattern({?MODULE, work, 1}, true, [local]), Pid ! go, Count = count(0), receive {done, Result} -> io:format("result: ~p~n", [Result]) after 1000 -> io:format("result: timeout~n") end, io:format("calls: ~p~n", [Count]). count(N) -> receive {trace, _Pid, call, {_Module, _Function, _Args}} -> count(N + 1); {done, Result} -> self() ! {done, Result}, N after 1000 -> N end. work(0) -> 0; work(N) -> N + work(N - 1).
erlc count_calls.erl
erl -noshell -eval 'count_calls:main(), halt().'
result: 15 calls: 6
Six calls for work(5): five, four, three, two, one and zero. The count clause puts the worker's answer back into the mailbox, because the count/1 loop consumed it on the way to the trace messages. A worker that was traced from another process may run before the pattern is set, which is why the worker waits for go: a trace set after the first call misses it.
The profilers of OTP
Four tools ship with OTP and answer four different questions. cprof counts calls per module, function and arity, exactly, with no timing: cprof:start/0 then cprof:analyse/1, and the module is in the tools application. eprof times every function a process runs, which finds the expensive function but perturbs the run. fprof traces the calls and writes a call graph with counts and times to a file, which is the tool for a question about who called whom. msacc samples the scheduler and answers where the runtime itself spends the time: emulator, garbage collection, ports and lock waits.
The reports of eprof and fprof carry times and process ids of the machine that produced them, so a page cannot quote one as stable output; the commands to run them are:
erl -pa _build/default/lib/*/ebin -eval 'cprof:start(), myapp:work(), io:format("~p~n", [cprof:analyse(myapp)]), halt().'
The command starts cprof, runs the program and prints the analysis, and it is marked as a command this page does not run: it needs the modules of a project on the code path. The reports of eprof:analyze/0 and fprof:analyse/1 are read on the machine that produced them, and a number copied into a page would be stale the day it was written.
observer is the graphical one: process tree, memory, load and a trace tool in one window. It needs wx and a display, so the course describes it without a screenshot; the observability lesson runs the calls that read the same numbers from a plain shell. The order to reach for them is: the log of a restart, the mailbox of the slow process, a count of calls, and only then a profiler.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
timer:tc(Fun)answer?Answer
{Microseconds, Value}The time comes back with the value, so a measurement keeps the answer.
-
Why is one run of a fun not a measurement?
Answer
The first run pays for code loading and the collector runs when it likes
A single run mixes the work with startup and garbage collection, so a benchmark repeats it.
-
Which call turns tracing on for a process?
Answer
erlang:trace/3trace/3names the process and the events, andtrace_pattern/3picks the functions. -
What does
erlang:trace_pattern(MFA, true, [local])select?Answer
The local calls of that function inside its module
The
localflag traces calls made inside the module, not calls from other modules. -
Which profiler counts calls exactly without timing them?
Answer
cprofcprof counts per module, function and arity, and its numbers do not depend on the machine.
-
What does
msaccmeasure?Answer
Where the runtime itself spends its time
It samples the scheduler and reports the emulator, the garbage collector, the ports and the locks.
-
What does this module print?
-module(q1). -export([main/0]). main() -> {Time, Value} = timer:tc(fun() -> length([a, b, c]) end), io:format("~p ~p~n", [Value, is_integer(Time)]).Answer
3 trueThe fun answers three, and the first element of the tuple is an integer number of microseconds.
-
What does this module print?
-module(q2). -export([main/0, work/1]). main() -> Self = self(), Pid = spawn(fun() -> receive go -> ok end, Self ! {done, work(3)} end), 1 = erlang:trace(Pid, true, [call]), 1 = erlang:trace_pattern({?MODULE, work, 1}, true, [local]), Pid ! go, Count = count(0), receive {done, R} -> io:format("~p ~p~n", [R, Count]) after 1000 -> io:format("timeout~n") end. count(N) -> receive {trace, _, call, _} -> count(N + 1); {done, R} -> self() ! {done, R}, N after 1000 -> N end. work(0) -> 0; work(N) -> N + work(N - 1).Answer
6 4work(3)sums to six and is called for three, two, one and zero, so four calls are traced. -
What does this module print?
-module(q3). -export([main/0]). main() -> {Algorithm, {Time, Value}} = {lists, timer:tc(lists, sum, [[1, 2, 3]])}, io:format("~p ~p ~p~n", [Algorithm, Value, is_integer(Time)]).Answer
lists 6 trueThe remote form times
lists:sum/1, which answers six, and the time is an integer. -
What does this module print?
-module(q4). -export([main/0]). main() -> io:format("~p~n", [element(1, timer:tc(fun() -> ok end)) >= 0]).Answer
trueThe time is a non-negative integer number of microseconds, so the comparison holds.
The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container. The reports of eprof and fprof were produced on this machine and are described, not quoted: their numbers change with the run.
Автор статьи: Arthur Isaev