2010-01-08 80 views

回答

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 
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> 

是的東西,你正在尋找?

+0

你讓我擔心! 你必須除以10^6才能得到正確的結果。 – t0il3ts0ap 2017-02-08 13:31:05