I was thinking about how to implement a process that gives the number of discrete intervals in time that occurred since it started. Am I losing accuracy here? How do I implement this without loss of accuracy after a while and after heavy client abuse. I am kind of stumped on how to do this in Erlang.
Naturally I don't want to use a system call such as now().
-module(clock).
-compile([export_all]).
start(Time) ->
register(clock, spawn(fun() -> tick(Time, 0) end)).
stop() -> clock ! stop.
tick(Time, Count) ->
receive
nticks ->
io:format("~p ticks have passed since start~n", [Count])
after 0 -> true
end,
receive
stop ->
void
after Time ->
tick(Time, Count + 1)
end.
Manual tick counting like you're doing is not going to be accurate due to slight scheduling fluctuations as well as function execution overhead.
What you want to do is grab a timestamp when the process starts and pass that in to each recursive call to the function. Then, when you want to grab the number of ticks (in microseconds) that have elapsed since you started the process, grab a new timestamp and pass them both into now_diff.
It looks like you're using your own concept of "ticks", so you can just figure out how many microseconds your "tick" is and divide your end result by it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With