开发者

How to measure time a function takes to execute from an erlang shell?

开发者 https://www.devze.com 2022-12-15 18:02 出处:网络
Is there is a simple way to measure a function\'s execution ti开发者_运维问答me if I run that function from an erlang shell?Please see the article Measuring Function Execution Time.

Is there is a simple way to measure a function's execution ti开发者_运维问答me if I run that function from an erlang shell?


Please see the article Measuring Function Execution Time.

It is all based on timer:tc/3 for the measurement.


If you want to measure an anonymous function:

1> TC = fun(F) -> B = now(), V = F(), A = now(), {timer:now_diff(A,B), V} end.

2> F = fun() -> lists:seq(1,1000) end.
3> TC(F).
{47000,
 [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,
  23,24,25,26,27|...]}

average of N runs:

4> TCN2 = fun(T,F,0) -> ok; (T,F,N) -> F(), T(T,F,N-1) end.
5> TCN = fun(F,N) -> B=now(), TCN2(TCN2,F,N), A=now(), timer:now_diff(A,B)/N end.

6> TCN(F, 1000).
63.0


I am learning Erlang and this is one of the exercise in the book, here it how I attempted it

lib_misc.erl

time_taken_to_execute(F) -> Start = os:timestamp(),
  F(),
  io:format("total time taken ~f seconds~n", [timer:now_diff(os:timestamp(), Start) / 1000]).

and on command-line, I do

1> lib_misc:time_taken_to_execute(fun() -> 1 end).
total time taken 0.003000 seconds
ok
2> lib_misc:time_taken_to_execute(fun() -> [Num || Num <- lists:seq(1, 100)] end).
total time taken 0.085000 seconds
ok
3> lib_misc:time_taken_to_execute(fun() -> [Num || Num <- lists:seq(1, 10000000)] end).
total time taken 9354.205000 seconds
ok
4> 

Is that something you were looking?

0

精彩评论

暂无评论...
验证码 换一张
取 消