使用Erlang的httpc
通过HTTP下载文件时,CPU利用率远远高于curl或wget。我用来衡量下载速度的代码可以在这篇文章的底部看到。
高CPU利用率存在问题,尤其是在低端设备上。我在ARM-SoC上运行Erlang,它比第一个Raspberry PI稍微强大一点,这段代码导致100%的CPU利用率和仅仅6.1 MiB / s的下载速度。使用curl和wget,CPU利用率保持在100%以下,并且几乎可以充分利用网络接口 (在100 MBit / s网络接口上为10.7 MiB / s或85.6 MBit / s)。
我尝试使用其他HTTP库,包括ibrowse和hackney,但同样的问题仍然存在。我的猜测是它与Erlang的套接字性能有关,但我可能错了。所以我的问题是,究竟是什么导致那些缓慢的下载速度,并且有任何解决方法吗?我知道像https://github.com/puzza007/katipo这样使用libcurl的库,因此可能不会有同样的问题,但我不想使用任何使用NIF的库。
defmodule DownloadPerformanceTest do
@testfile 'http://speed.hetzner.de/100MB.bin'
@filesize 104857600
@save_to '/dev/null'
def test() do
Application.start(:inets)
then = :erlang.system_time(:micro_seconds)
{:ok, :saved_to_file} = :httpc.request(:get, {@testfile, []}, [], [{:stream, @save_to}])
now = :erlang.system_time(:micro_seconds)
diff = now - then
bw = bandwidth_to_human_readable(@filesize, diff)
IO.puts "Download took #{:erlang.trunc(diff / 1_000_000)} seconds, average speed: #{bw}"
end
defp bandwidth_to_human_readable(bytes, microseconds) do
bytes_per_second = bytes / (microseconds / 1000000)
exponent = :erlang.trunc(:math.log2(bytes_per_second) / :math.log2(1024))
prefix = case exponent do
0 -> {:ok, ""}
1 -> {:ok, "Ki"}
2 -> {:ok, "Mi"}
3 -> {:ok, "Gi"}
4 -> {:ok, "Ti"}
5 -> {:ok, "Pi"}
6 -> {:ok, "Ei"}
7 -> {:ok, "Zi"}
8 -> {:ok, "Yi"}
_ -> {:error, :too_large}
end
case prefix do
{:ok, prefix} ->
quantity = Float.round(bytes_per_second / :math.pow(1024, exponent), 2)
unit = "#{prefix}B/s"
"#{quantity} #{unit}"
{:error, :too_large} ->
"#{bytes_per_second} B/s"
end
end
end
答案 0 :(得分:1)
回到benchmark,三个明确的问题,我能够确定
/dev/null
,但文件保存会产生费用。有一次,我在download_loop_hackney()
删除了保存操作,hackney是最快的
defp download_loop_hackney(client, file) do
case :hackney.stream_body(client) do
{:ok, _result} ->
#IO.binwrite(file, result)
download_loop_hackney(client, file)
:done ->
:ok = File.close(file)
end
end
基准数字因此
download_http: download took 0 seconds, average speed: 211.05 MiB/s
download_ibrowse: download took 0 seconds, average speed: 223.15 MiB/s
download_hackney: download took 0 seconds, average speed: 295.83 MiB/s
download_tcp: download took 0 seconds, average speed: 595.84 MiB/s