zoukankan      html  css  js  c++  java
  • [Erlang35]Erlang18的time

    在Erlang 18中, 我们还是可以使用erlang:now/0

    但也已经 deprecated啦,大量使用可能引发瓶颈。

    The default time warp mode has the same behavior as before, and the old API still works. Thus, you are not required to change anything unless you want to. However, you are strongly encouraged to use the new API instead of the old API based onerlang:now/0erlang:now/0 is deprecated, as it is and will be a scalability bottleneck.

    By using the new API, you automatically get scalability and performance improvements. This also enables you to use the multi-time warp mode that improves accuracy and precision of time measurements.

    具体问题分析可以看看余峰2013年写的。总的就是,有锁,大规模使用可能会引起POSIX time jumping,进而可能不准确。

    1. 原来我们取系统时间用的是 erlang:now/0, 在新版API中我们使用erlang:system_time/0代替

    1> erlang:system_time().
    1456761315297998397

    它返回的是当前的 Erlang system time in native time unit. 如果你还是需要原来的erlang:now/1的三元组方式,可以使用

    2> erlang:timestamp().
    {1456,761486,888869}

    那么我们怎么衡量上面说的time unit(时间最小单元)使用convert_time_unit/3把1s转为最小单元是纳秒

    3> erlang:convert_time_unit(1, seconds, native).
    1000000000

    再看

    4> Fun = fun() -> Begin = erlang:monotonic_time(), timer:sleep(5000), End = erlang:monotonic_time(), End - Begin end.
    #Fun<erl_eval.20.54118792>
    5> Fun().
    5005813139

    得到的结果,根本不是5000000000整。多运行几次Fun().会发现每次的结果都不一样。

    2.以前我们经常使用erlang:now/0来规定事件的先后顺序,因为它是单调递增的。

    现在我们有了新的API. 

    6> erlang:unique_integer([monotonic]).
    -576460752303423487

    这个函数可以帮组我们产生单调数字,但是仅限于同一个runtime system instance。 如果多节点的分布式系统中,就无法保证单调。

    如果你想记录事件发生时的顺序和时间。那么可以使用一个二元tuple

    7> {erlang:monotonic_time(), erlang:unique_integer([monotonic])}.
    {-576458615893212445, -576460752303423487}

    如果还要加上系统时间就可以再加上

    8> {erlang:monotonic_time(), erlang:unique_integer([monotonic]), erlang:system_time()}.
    {-576457144539468688,-576460752303423488,1456762913149935455}

    3.如果你只是想产生一个唯一的标示。那么可以使用

    9> erlang:unique_integer().
    -576460752303423452

    或者使用正数的

    10> erlang:unique_integer([positive]).
    45

    4.生成随机数

    以前使用erlang:now/0和random.seed生成随机数。现在可以使用

    11> random:seed(erlang:monotonic_time(), erlang:unique_integer(), erlang:monotonic_time()).
    undefined
    12> random:uniform().
    0.03920785389270476

    5.总结.

    不要再使用erlang:now/0啦!

    如果你想兼容以前的旧代码,那么快快来看这个官方的例子是怎么做到的:)

    https://github.com/erlang/otp/blob/maint/erts/example/time_compat.erl

    官方关于time的文档:

    http://erlang.org/doc/apps/erts/time_correction.html


    When my code crashes all the time, but restarts without anybody knowing

  • 相关阅读:
    shell加载配置文件
    Shell四种运行方式(启动方式)
    Linux下Fork与Exec使用
    ln -snf 的个人理解
    利用python3将已有的某几个pptx文件的某些slides来生成新的pptx文件的范例
    如何在centos7中安装python3
    ng-include
    ng-class细说 by破狼
    AngularJS的Filter用法详解
    理解angularjs中的$emit,$broadcast和$on by Four
  • 原文地址:https://www.cnblogs.com/zhongwencool/p/erlang_timer_18.html
Copyright © 2011-2022 走看看