我在 Eclipse 中运行了下面的代码。代码已编译,并在 Eclipse 工作区的
.txt
文件夹中创建 scr
文件,并将数据头传递给第一个 io:format
,但 second io:format
抛出错误参数错误,我不知道如何解决。
%% @author PC
%% @doc @todo Add description to pingping.
-module(pingping).
-export([run/2, run/3]).
-include("conf.hrl").
run(DataSize, R) ->
OutFileLocation = "out_cerl_pingping.txt",
case file:open(OutFileLocation, [append]) of
{error, Why} ->
?ERR_REPORT("L'archivio non esiste!", Why);
{ok, OutFile} ->
run(DataSize, R, OutFile)
end.
run(DataSize, R, OutFile) ->
Data = generate_data(DataSize),
Self = self(),
SpawnStart = time_microseg(),
P1 = spawn(fun() -> pingping(Data, Self, R) end),
P2 = spawn(fun() -> pingping(Data, Self, R) end),
SpawnEnd = time_microseg(),
TimeStart = time_microseg(),
P1 ! {init, self(), P2},
P2 ! {init, self(), P1},
finalize(P1),
finalize(P2),
TimeEnd = time_microseg(),
TotalTime = TimeEnd - TimeStart,
SpawnTime = SpawnEnd - SpawnStart,
printResult(Data, R, TotalTime, SpawnTime, OutFile).
pingping(_, Parent, 0) ->
Parent ! {finish, self()};
pingping(Data, Parent, R) ->
receive
{init, Parent, Peer} ->
Peer ! {self(), Data},
pingping(Data, Parent, R-1);
{Peer, _} ->
Peer ! {self(), Data},
pingping(Data, Parent, R-1)
end.
finalize(Pid) ->
receive
{finish, Pid} -> ok
end.
printResult(Data, R, Time_exec, Time_spawn, OutFile) ->
FormatH = "~-9s\t ~-13s\t ~-22s\t ~-11s\t ~-10s~n",
Header = ["#bytes", "#repetitions", "exec_time[microsec]", "MBytes/sec", "spawn_time"],
io:format(OutFile, FormatH, Header),
MBps = bandwidth_calc(Data, Time_exec),
FormatD = "~-9w\t ~-13w\t ~-22f\t ~-11f\t ~-3f~n",
io:format(OutFile,FormatD, [size(Data), R, Time_exec, MBps, Time_spawn ]).
bandwidth_calc(Data, Time) ->
Megabytes = (size(Data) / math:pow(2, 20)),
Seconds = (Time * 1.0e-6),
Megabytes / Seconds.
generate_data(Size) -> generate_data(Size, []).
generate_data(0, Bytes) ->
list_to_binary(Bytes);
generate_data(Size, Bytes) ->
generate_data(Size - 1, [1 | Bytes]).
time_microseg() ->
{MS, S, US} = now(),
(MS * trunc(1.0e+12)) + (S * trunc(1.0e+6)) + US.
%-define(OUT_FILE, "erl_out.txt").
-define(ERR_REPORT(Msg, Reason), io:format("%%%%%%%%%%%%%% ERROR %%%%%%%%%%%%%%\n" ++
"Msg: ~s\n" ++
"Reason: ~s\n\n", [Msg, Reason])).
您的代码无法编译,因为未显示
conf.hrl
包含文件,所以我猜测它提供了底部提供的 ERR_REPORT
宏。您没有包含有关如何运行代码的说明,因此我猜测并调用了 pingping:run(3, 3).
,这导致了 Erlang/OTP 26.1 下的此错误:
** exception error: bad argument
in function io:format/3
called as io:format(<0.95.0>,"~-9w\t ~-13w\t ~-22f\t ~-11f\t ~-3f~n",
[3,3,23,0.12439230213994565,6])
*** argument 3: element 3 must be of type float
element 5 must be of type float
错误消息给了我们答案:您正在尝试将整数打印为浮点数。更改此行:
FormatD = "~-9w\t ~-13w\t ~-22f\t ~-11f\t ~-3f~n",
为了更正元素 3 和 5 的格式,请执行以下操作:
FormatD = "~-9w\t ~-13w\t ~-22w\t ~-11f\t ~-3w~n",
导致
pingping:run(3, 3)
返回 ok
以及包含以下内容的 out_cerl_pingping.txt
文件:
#bytes #repetitions exec_time[microsec] MBytes/sec spawn_time
3 3 15 0.190735 5