erlangtsungerlang-escript

In Tsung, how can I get publish message time in milisec?


In Tsung, I want publish message time in milisec, I tried below but able to get time in Sec only.

<setdynvars sourcetype="eval" code='fun({Pid,DynVars})->
{{Year,Month,Day},{Hour,Minute,Second}} = erlang:localtime(),
io_lib:format(&apos;~4..0B-~2..0B-~2..0B::~2..0B:~2..0B:~4..0B\n&apos;, [Year,Month,Day,Hour,Minute,Second]) end.'>
<var name="time" />
</setdynvars> 

<request subst="true">

                <mqtt type="publish" topic="xxx" qos="0" retained="true">%%_time%%</mqtt>

            </request>

Solution

  • you can use

    1> Time_milli = fun() -> 
           Um = erlang:system_time(milli_seconds),
           {D,T} = calendar:gregorian_seconds_to_datetime(Um div 1000 + 719528*86400)
           {D,T,Um rem 1000}
       end.
    #Fun<erl_eval.20.54118792>
    2> Time_milli().                                                                
    {{2015,12,9},{8,13,53},40}
    

    The value 719528*86400 is the number of seconds between the 1 1 1 at 0 0 0 and the 1970 1 1 at 0 0 0.

    Note: the system_time is not monotonic, if you need this feature you can use erlang:monotonic_time/1, but in this case you cannot convert to a date or compare between different nodes.