Skip to content

Instantly share code, notes, and snippets.

@holyxiaoxin
Last active February 11, 2016 04:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save holyxiaoxin/fe23d044550fa4b1493e to your computer and use it in GitHub Desktop.
Save holyxiaoxin/fe23d044550fa4b1493e to your computer and use it in GitHub Desktop.
Async vs Sync http requests
defmodule Tasks do
def main(_args) do
HTTPoison.start
# data gov caches the requests so i had to spin up a json server,
# which does not have caching to accurately test the async/sync time.
urls = [
"https://data.gov.uk/data/api/service/transport/planned_road_works/road?road=M62",
"https://data.gov.uk/data/api/service/transport/planned_road_works/road?road=M62",
]
{microsec, _} = :timer.tc fn ->
urls
|> Enum.map(fn(url) -> Task.async(fn -> HTTPoison.get(url,[],timeout: 1500) end) end)
|> Enum.map(&Task.await(&1, 30000))
|> Enum.each(fn({status, result}) ->
if (status == :ok) do
IO.inspect result.status_code
else
IO.inspect result.reason
end
end)
end
IO.puts "async took #{microsec} microsecs"
{microsec, _} = :timer.tc fn ->
urls
|> Enum.map(fn(url) -> HTTPoison.get(url,[],timeout: 1500) end)
|> Enum.each(fn({status, result}) ->
if (status == :ok) do
IO.inspect result.status_code
else
IO.inspect result.reason
end
end)
end
IO.puts "sync took #{microsec} microsecs"
end
end
@holyxiaoxin
Copy link
Author

➜  tasks git:(master) ✗ mix escript.build && ./tasks
Compiled lib/tasks.ex
Generated escript tasks with MIX_ENV=dev
number of urls: 1
async took 0.403556 seconds
sync took 0.029024 seconds
➜  tasks git:(master) ✗ mix escript.build && ./tasks
Compiled lib/tasks.ex
Generated escript tasks with MIX_ENV=dev
number of urls: 4
async took 0.474734 seconds
sync took 0.072134 seconds
➜  tasks git:(master) ✗ mix escript.build && ./tasks
Compiled lib/tasks.ex
Generated escript tasks with MIX_ENV=dev
number of urls: 24
async took 1.43528 seconds
sync took 0.872841 seconds
➜  tasks git:(master) ✗ mix escript.build && ./tasks
Compiled lib/tasks.ex
Generated escript tasks with MIX_ENV=dev
number of urls: 96
async took 2.752861 seconds
sync took 3.302035 seconds
➜  tasks git:(master) ✗ mix escript.build && ./tasks
Compiled lib/tasks.ex
Generated escript tasks with MIX_ENV=dev
number of urls: 384
async took 9.253165 seconds
sync took 20.645522 seconds

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment