二、测试代码运行时间
1、场景描述
都说Erlang牛逼,高性能,但是执行效率真的很高吗?这个倒真不见得,感兴趣的,可以去测试下每行Erlang代码的运行时间,你会发现,Erlang的执行效率不见得比C或者是C++高。
2、API函数
tc(Module, Function, Arguments) -> {Time, Value}
Types:
Module = module()
Function = atom()
Arguments = [term()]
Time = integer()
In microseconds
Value = term()
Evaluates apply(Module, Function, Arguments) and measures the elapsed real time as reported by os:timestamp/0. Returns {Time, Value}, where Time is the elapsed real time in microseconds, and Value is what is returned from the apply.
3、实例
-module(myring).
-export([start/1, start_proc/2]).
start(Num) ->
start_proc(Num, self()).
start_proc(0, Pid) ->
Pid ! ok;
start_proc(Num, Pid) ->
NPid = spawn(?MODULE, start_proc, [Num-1, Pid]),
NPid ! ok,
receive ok -> ok end.
运行过程
Eshell V5.9.1 (abort with ^G)
1> c(myring).
{ok,myring}
2> timer:tc(myring, start, 1000000). %%Arguments = [term()]
** exception error: bad argument
in function apply/3
called as apply(myring,start,1000000)
in call from timer:tc/3 (timer.erl, line 194)
3> timer:tc(myring, start, [1000000]).
{2375954,ok} %%时间单位为 us
4>