如何测量函数从erlang shell执行的时间?

时间:2010-01-08 23:43:30

标签: erlang

如果我从erlang shell运行该函数,是否有一种简单的方法来测量函数的执行时间?

3 个答案:

答案 0 :(得分:18)

请参阅文章Measuring Function Execution Time

全部基于timer:tc/3进行测量。

答案 1 :(得分:3)

如果要测量匿名函数:

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|...]}

N次运行的平均值:

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

答案 2 :(得分:0)

我正在学习Erlang,这是书中的练习之一,在这里我是如何尝试的

<强> 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]).

并在command-line,我做

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> 

你看到的是什么吗?