Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accurate clock in Erlang

Tags:

erlang

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.
like image 414
buddhabrot Avatar asked Dec 27 '10 14:12

buddhabrot


1 Answers

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.

like image 51
ryeguy Avatar answered Nov 07 '22 12:11

ryeguy