Skip to content

Instantly share code, notes, and snippets.

@kenpratt
Created January 18, 2010 06:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kenpratt/279841 to your computer and use it in GitHub Desktop.
Save kenpratt/279841 to your computer and use it in GitHub Desktop.
-module(stopwatch_client).
-export([start_timer/0, stop_timer/0, read_timer/0]).
start_timer() ->
stopwatch_server ! {self(), start_timer}.
stop_timer() ->
stopwatch_server ! {self(), stop_timer}.
read_timer() ->
stopwatch_server ! {self(), read_timer},
receive
{stopwatch_server, Value} ->
Value
end.
-module(stopwatch_server).
-export([start/0, stop/0]).
-record(state, {mode = stopped,
start_time = undefined,
stop_time = undefined}).
start() ->
Pid = spawn(fun() -> loop(#state{}) end),
true = register(stopwatch_server, Pid),
io:format("Stopwatch server started~n"),
ok.
stop() ->
self() ! {self(), shutdown}.
loop(State) ->
receive
{_From, shutdown} ->
io:format("Stopwatch server is shutting down~n"),
ok;
{_From, start_timer} ->
StartTime = now(),
io:format("Stopwatch started~n"),
loop(State#state{mode = running, start_time = StartTime});
{_From, stop_timer} ->
StopTime = now(),
io:format("Stopwatch stopped~n"),
loop(State#state{mode = stopped, stop_time = StopTime});
{From, read_timer} ->
case State#state.mode of
running ->
Now = now(),
Diff = calc_diff(Now, State#state.start_time),
From ! {stopwatch_server, Diff};
stopped ->
Diff = calc_diff(State#state.stop_time, State#state.start_time),
From ! {stopwatch_server, Diff}
end,
loop(State)
end.
calc_diff(T2, T1) ->
DiffMicroSecs = timer:now_diff(T2, T1),
round(DiffMicroSecs / 1000).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment