[erlang-questions] Lockfree now()

Erik Søe Sørensen <>
Fri Jul 13 10:35:48 CEST 2012


Oh, but you do have a choice between more than one time source in Erlang:
now() - as known, for microsecond-precision and uniqueness
erlang:universaltime() and friends - for second-precision and YMD-HMS
format.
os:timestamp() - for microsecond-precision but without uniqueness and time
correction.

For many places where you could use now() but simply need a timestamp for
logging or the like, os:timestamp() might be more appropriate and a bit
more lightweight. Its return type is compatible with that of now().

2012/7/13 Wojtek Narczyński <>

>  On 2012-07-12 23:55, Erik Søe Sørensen wrote:
>
> 2012/7/12 Wojtek Narczyński <>
>
>> On 07/12/2012 08:23 PM, Erik Søe Sørensen wrote:
>>
>>> Because of atomic operations.
>>> I may not have been explicit enough there: latest_now is a
>>> java.util.concurrent.AtomicLong, and the two updating accesses to it are
>>> atomic.
>>>                 long prev;
>>>                 while ((prev = latest_now.get()) < micros) {
>>>                         if (latest_now.compareAndSet(prev,micros)) {
>>>                                 return micros;
>>>                         }
>>>                 }
>>>                 return latest_now.incrementAndGet();
>>>
>>> This - and only because of this - means that no lock is necessary.
>>>
>>  Oh, I think I understand now.
>>
>> You want to have one coarse-grained clock - protected by a lock, and
>> another one fine-grained - updated atomically.
>>
>> Do I understand correctly now?
>>
>
>  Indeed :-)
>
>
> I looked into the Erjang repo, and indeed now_unique_micros() looks good,
> so I honorably retreat.
>
>
> This is more or less what already happens, at
>
> https://github.com/erlang/otp/blob/master/erts/emulator/beam/erl_time_sup.c
> line 172. The variant at line 262 and forth is somewhat more complex to
> follow; I'm afraid it doesn't follow the pattern as things are.
>
>
> I suspect that there are some serious differences between platforms,
> because on Unix the POSIX API (clock_gettime and friends) is a clean one -
> you have a choice of different clocks with different characteristics.
> Erlang exposes only one clock, the most expensive one possible - strictly
> increasing [0, 1, 2, 3, ...], basically a clock and a counter in one. Using
> atomic operations instead of locks would definitely be faster. But still
> slower compared with an increasing clock [0, 1, 1, 2, ...], and other
> clocks. Certainly, it would be nice to have that POSIX choices in erlang. I
> have been surprised once by erlang:now() performance on multiclore, but
> still I do not think this is big issue.
>
> --Regards,
> Wojtek
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20120713/cde70372/attachment.html>


More information about the erlang-questions mailing list