How to resolve the algorithm Rate counter step by step in the Erlang programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Rate counter step by step in the Erlang programming language
Table of Contents
Problem Statement
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: Be aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can. See also: System time, Time a function
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Rate counter step by step in the Erlang programming language
Source code in the erlang programming language
-module( rate_counter ).
-export( [fun_during_seconds/2, task/0] ).
fun_during_seconds( Fun, Seconds ) ->
My_pid = erlang:self(),
Ref = erlang:make_ref(),
Pid = erlang:spawn( fun() -> fun_during_seconds_loop( My_pid, Fun ) end ),
timer:send_after( Seconds * 1000, My_pid, {stop, Ref} ),
N = fun_during_seconds_receive_loop( Ref, Pid, 0 ),
erlang:exit( Pid, kill ),
N.
task() ->
Results = [timer:tc( fun() -> io:fwrite("Hello, world!~n") end ) || _X <- lists:seq(1, 3)],
Times = [X || {X, _Returned} <- Results],
io:fwrite( "Times ~p, average ~p microseconds.~n", [Times, lists:sum(Times) / erlang:length(Times)]),
N = fun_during_seconds( fun() -> math:sqrt(123) end, 2 ),
io:fwrite( "Square root of 123, during 2 seconds, was done ~p times.~n", [N] ).
fun_during_seconds_loop( Pid, Fun ) ->
Fun(),
Pid ! {one_time, erlang:self()},
fun_during_seconds_loop( Pid, Fun ).
fun_during_seconds_receive_loop( Ref, Pid, N ) ->
receive
{stop, Ref} -> N;
{one_time, Pid} -> fun_during_seconds_receive_loop( Ref, Pid, N + 1 )
end.
You may also check:How to resolve the algorithm Generate Chess960 starting position step by step in the Wren programming language
You may also check:How to resolve the algorithm Apply a callback to an array step by step in the Nemerle programming language
You may also check:How to resolve the algorithm Sum multiples of 3 and 5 step by step in the F# programming language
You may also check:How to resolve the algorithm Loops/Break step by step in the Maple programming language
You may also check:How to resolve the algorithm Simulate input/Keyboard step by step in the Phix programming language