Efficient way to read data from a socket while calculating instant bitrate
Sebastien Merle
s.merle@REDACTED
Thu Jul 30 13:17:23 CEST 2009
Hi,
I am reading data from a socket, and I want to be able to calculate
the instant bitrate over a period of time.
I am currently doing something like:
download(Sock, Monitor) ->
erlang:send_after(?MONITORING_PERIOD, self(), {monitor}),
download(Sock, Monitor, erlang:now(), 0).
download(Sock, Monitor, LastTime, BytesDelta) ->
ok = inet:setopts(Sock, [{active, once}]),
receive
{tcp, Sock, Data} ->
download(Sock, Monitor, LastTime, BytesDelta + size(Data));
{tcp_closed, Sock} -> ok;
{monitor} ->
Now = erlang:now(),
TimeDelta = timer:now_diff(Now, LastTime),
Rate = (BytesDelta * 1000000) div TimeDelta,
Monitor ! {rate, self(), Rate},
erlang:send_after(?MONITORING_PERIOD, self(), {monitor}),
download(Sock, Monitor, Now, 0)
end.
This is working, but with very high bitrates it seems rather inefficient because
it receives a lot of small messages.
It request the packets one by one by calling inet:setopts because it does
some client-side rate control at the same time (not included in the
sample code).
Any suggestions to make this more efficient ?
Regards,
Sebastien Merle.
More information about the erlang-questions
mailing list