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

Per Hedeland per@REDACTED
Sat Feb 21 23:16:44 CET 2009


James Hague <james.hague@REDACTED> wrote:
>
>I get this:
> {{4999999,5000000},{460636,1451}}
>
>This is using a 64-bit version of Window Vista, "Erlang (BEAM)
>emulator version 5.6.5 [smp:4] [async-threads:0]".

Eeew, Windows - according the sources, gettimeofday() is there replaced
by GetSystemTime() with SystemTimeToFileTime() applied to the result. I
have no idea what those functions actually do (nor what the quality of
the resulting numbers is), but it would appear that they finish it in a
quarter of a microsecond or so on your box, i.e. now-bumping will kick
in.

You could try what I suggested a few messages back, "don't call it so
often" - i.e. twiddle your thumbs for a while in each loop round, to
make sure the now/0 calls are separated by at least a microsecond. The
below causes some 3 microseconds of twiddling in my tests on a 3GHz CPU,
adjust to taste (weird argument-passing-around to prevent it from being
optimized away, may not be necessary).

time3(N) -> time3(N, now(), 0, [0]).
time3(N, Start, C, X) ->
    case timer:now_diff(now(), Start) of
        M when M >= N -> {C, M};
        _ -> time3(N, Start, C+1, twiddle(X))
    end.

twiddle(X) ->
    [hd(X)|[Y*Y || Y <- lists:duplicate(5, 12345678901234567890123456789)]].


Fredrik Svahn <fredrik.svahn@REDACTED> wrote:
>
>I get the same results as James when running R12B-5 on Windows Vista. It
>seems to be related to the algorithm for adjusting to sudden time changes.
>When disabling it with the "+c" flag it works (almost) as expected.

Hm, this would imply that the numbers that the ersatz gettimeofday() on
Windows returns are more or less garbage, no surprise there I guess - or
possibly that the algorithm has bad assumptions on how to get "really
elapsed time" on Windows [Vista] (great fun was had when it tried to use
times() on FreeBSD back when times() was based on gettimeofday() - the
emulator stopped dead in its tracks). FWIW, it uses GetTickCount() for
that, which sounds reasonable, but who knows...

In either case, the twiddling suggested above may not help then, but
it's worth a try I think. Disabling the algorithm is probably
undesirable.

--Per



More information about the erlang-questions mailing list