Take the 2-minute tour ×

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().


start(Time) ->
    register(clock, spawn(fun() -> tick(Time, 0) end)).

stop() -> clock ! stop.

tick(Time, Count) ->
        nticks ->
            io:format("~p ticks have passed since start~n", [Count])
    after 0 -> true
        stop ->
    after Time ->
            tick(Time, Count + 1)
share|improve this question
add comment

1 Answer

up vote 10 down vote accepted

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.

share|improve this answer
Yes I suppose that is the easiest way.. I can still use the concept of "tick resolution" with the "after.." timeout, to reduce the number of recursive calls that are made. –  buddhabrot Dec 27 '10 at 15:33
add comment

Your Answer


