[erlang-questions] writing a delay loop without now()

James Hague <>
Sat Feb 21 00:43:53 CET 2009

All right, here's a simple case.  I hope I'm not doing something dumb
here.  This is only to illustrate one issue; it's not a full analysis
of timing in Erlang.

First, try this from the shell:


I get {57018,5007} which is just about five seconds (the second number
is the elapsed time between calls.  The parameter to sleep is in
MILLIseconds.  (Note that if I change 5000 to 1, I get a result of 16
milliseconds elapsed on the machine I'm using at the moment.  If I
change it to 16, I get a result of 31 milliseconds.)

Now here's a little function that uses now/0 and timer:now_diff/2 to
wait for a specified number of MICROseconds:


time(N) -> time(N, now()).
time(N, Start) ->
	case timer:now_diff(now(), Start) of
		M when M >= N -> M;
		_ -> time(N, Start)

Now try it from the shell:


I get {836723,1310} on the same machine.  1.3 seconds.

More information about the erlang-questions mailing list