aungkoko
How can I get the response time of a HTTP request in elixir?
I am doing some monitoring for my api endpoints. I’ve already tried out with some http clients like httpoison, and hackney erlang library. But they don’t give me http response time, do they? Did someone experience kind of this? It would be grateful if someone can help me out.
Most Liked
dom
I tend to do something like
{microseconds, result} = :timer.tc(fn -> do_the_request(...) end)
milliseconds = System.convert_time_unit(microseconds, :microseconds, :millisecond)
yurko
I do this
start_ms = System.monotonic_time(:milliseconds)
# do the request and receive response
end_ms = System.monotonic_time(:milliseconds)
diff = end_ms - start_ms
idi527
I don’t know if that would work for you (I’ve seen it being used in knutin/elli), but if all of your work is done in a single process, you can put timings into the process dictionary:
defp t(key) do
:erlang.put({:time, key}, :os.timestamp())
end
and call it in different places inside the same process
t(:start_request)
# request something
t(:done_requesting)
t(:start_parsing_body)
# parse body
t(:done_parsing_body)
and then collect the timings at some point later (you would need to be in the same process though).
Enum.flat_map(:erlang.get(), fn
{{:time, event} = key, time} ->
:erlang.erase(key)
[{event, time}]
_ ->
[]
end)
which would return something like
timings = [start_request: {1518, 275996, 334820}, done_requesting: {1518, 276000, 54915}]
and you can calculate diffs with :timer.now_diff/2
start_request = timings[:start_request]
done_requesting = timings[:done_requesting]
:timer.now_diff(done_requesting, start_request)
#=> 3720095 (microseconds)
You might want to read Two frequently used system calls are ~77% slower on AWS EC2 if you are on xen. I think beam uses these calls if it is compiled with --enable-gettimeofday-as-os-system-time and erl_xcomp_clock_gettime_cpu_time set to yes, but I might be wrong.
hristonev
I need this time too. I was thinking to measure it by system timer
probably will do the job.
cmkarlsson
Agreed. There can be quite a bit of difference here, especially when the HTTP client pool is overloaded. The function execution time can be large, even if the response time is faster.
Hackney though has metrics. (See Metrics on https://github.com/benoitc/hackney). It seems like it is tracking request and response times among other things. Perhaps it is closer to what you want.
It supports two erlang metrics libraries, but you can write your own as long as you implement the correct contract for your module if folsom or exometer is not your cup of tea or hard to integrate into elixir (I have no idea here).







