1 min read

Measuring function execution time in Elixir

In some cases, when we're dealing with critical parts of our apps, we want to get some insight into the performance of our code. A relevant piece of information is the time it takes a function to execute.  

Let's call that function CriticalModule.sleepy_func():

defmodule CriticalModule do
    def sleepy_func() do
        Process.sleep(1000)
    end
end

An easy way to measure the time is by wrapping the function call in a helper function that does the measurement, prints it and returns the result.

Let's define it in a debugging module.

defmodule Debugging do
  def measure(label, func) when is_function(func) do
    {microseconds, result} = :timer.tc(func)

    IO.puts IO.ANSI.blue() <> "#{label}: Finished in: #{microseconds / 1_000_000} seconds"

    result
  end
end

Then we can use it as follows:

This is great, but it isn't very friendly with the pipe operator, which is commonly used in Elixir. To fix this, we can write another version of the measure function.

def measure(arguments, func, label) when is_function(func) do
    {microseconds, result} = :timer.tc(fn -> func.(arguments) end)

    IO.puts IO.ANSI.blue() <> "#{label}: Finished in: #{microseconds / 1_000_000} seconds"

    result
end

Then: