1

这是一个简单而著名的测试脚本:

-module(processes).
-compile(export_all).

max(N)->
    Max=erlang:system_info(process_limit),
    io:format("the max processes is ~p ~n",[Max]),
    statistics(runtime),
    statistics(wall_clock),
    L=for(1,N,fun()->spawn(fun()->wait() end) end),
    {_,Time1}=statistics(runtime),
    {_,Time2}=statistics(wall_clock),
    lists:foreach(fun(Pid)->Pid!die end,L),
    U1=Time1*1000/N,
    U2=Time2*1000/N,
    io:format("the proecess time is ~p:~p ~n",[U1,U2]).

wait()->
    receive
        die->void
    end.

for(N,N,F)->[F()];
for(I,N,F)->[F()|for(I+1,N,F)].

main([])->
    max(100000).

这是erl的输出:

$ erl 
Erlang/OTP 17 [erts-6.2] [source] [64-bit] [smp:2:2] [async-threads:10] [kernel-poll:false]

Eshell V6.2  (abort with ^G)
1> c(processes)
1> processes:max(100000).
* 2: syntax error before: processes
1> c(processes).         
{ok,processes}
2> processes:max(100000).
the max processes is 262144 
the proecess time is 1.1:4.35 
ok

这是escript的输出:

$ escript processes.erl
the max processes is 262144 
the proecess time is 47.8:83.4

escript和erl之间的确切区别是什么?我是erlang的新手,请帮忙!

编辑:

当 escript 运行梁文件时,它输出与 erl 相同的结果:

$ escript processes.beam
the max processes is 262144 
the proecess time is 1.8:3.33

发生什么了?我知道 *.beam 是编译代码,但是 escript 在运行之前不编译脚本?我仍然很困惑。

4

1 回答 1

1

不同之处在于您的第二次运行被解释,而您的第一次运行被编译。跑

escript -c processes.erl

你会得到一个基本相同的时间。您还可以通过将指令-mode(compile).放入脚本中来获得此行为。

文档中

解释代码的执行比编译代码慢。如果大部分执行发生在解释代码中,编译它可能是值得的,即使编译本身需要一点时间。也可以提供 native 而不是 compile,这将使用 native 标志编译脚本,再次取决于 escript 的特性,这可能值得或不值得。

如前所述,可以有一个包含预编译光束代码的脚本。在预编译脚本中,脚本头的解释与包含源代码的脚本完全相同。这意味着您可以通过在文件前面加上以 #! 开头的行来使梁文件可执行。和 %%!上文提到的。在预编译脚本中,必须导出函数 main/1。

如果您对预编译选项感兴趣,您可能需要查看构建工具rebar,它有一个escriptize命令可以将您的所有代码转换为带有适当 escript 标头的预编译存档。

对于使用的解释/编译机制,您可以查看源代码到 escript。您将看到模式中的 escript 等效于(以某些语法为模)将您的代码逐行interpret粘贴到交互式解释器中。erl

于 2015-07-01T11:19:42.290 回答