erlang:now()如何工作?

wiz*_*awu 2 erlang eshell

-module(test_now).

-compile(export_all).

start() ->  
    {_, A, _} = now(),
    loop(0, A).

loop(A) ->  
    {_, B, _} = now(),  
    if   
        B == A + 1 -> loop(0, B);  
        true -> loop(A)  
    end.  

loop(T, B) ->
    {_, C, _} = now(),
    if 
        C == B + 1 -> io:write(T);
        true -> loop(T+1, B)
    end.
Run Code Online (Sandbox Code Playgroud)

逻辑上这个代码应该运行1+第二.但结果迅速恢复,远远不到一秒钟.如果我经常test_now:start()在Eshell中调用(向上箭头,输入,向上箭头,输入...),结果总是如此.999999ok

hdi*_*ima 9

从文档(现在/ 0):

还保证随后对此BIF的调用会不断返回增加的值.因此,now()的返回值可用于生成唯一的时间戳,如果在快速机器上的紧密循环中调用它,则节点的时间可能会变得偏斜.

所以你不能使用now/0来检查你的例子中的时间.您可以尝试使用os:timestamp/0代替:

start() ->  
    {_, S, MS} = os:timestamp(),
    loop(0, {S, MS}).

loop(T, {S, MS}=Start) ->
    {_, S2, MS2} = os:timestamp(),
    if 
        S2 == S + 1 andalso MS2 == MS -> io:format("~p~n", [T]);
        true -> loop(T + 1, Start)
    end.
Run Code Online (Sandbox Code Playgroud)

例:

1> timer:tc(test_timestamp, start, []).
13600591
{1000047,ok}
Run Code Online (Sandbox Code Playgroud)

但是,如果您只想在一秒钟内获得一些通知,请考虑使用erlang:send_after/3erlang:start_timer/3:

start() ->  
    erlang:send_after(1000, self(), timeout),
    loop(0).

loop(T) ->
    receive
        timeout -> io:format("~p~n", [T])
    after
        0 -> loop(T + 1)
    end.
Run Code Online (Sandbox Code Playgroud)

例:

1> timer:tc(test_timer, start, []).
27433087
{1000520,ok}
Run Code Online (Sandbox Code Playgroud)

  • 要生成唯一键,还要考虑[erlang:make_ref/0](http://www.erlang.org/doc/man/erlang.html#make_ref-0)或[crypto:rand_bytes/1](http:// www.erlang.org/doc/man/crypto.html#rand_bytes-1),[crypto:rand_uniform/2](http://www.erlang.org/doc/man/crypto.html#rand_uniform-2) (2认同)