Implement a Basic block/yield with Elixir

Mustafa Turan
ElixirLabs
Published in
1 min readFeb 23, 2017

With powerful macros, Elixir language allows you to code magic without pain. Sometimes, you might need to run a snippet of code before and after execution of a block of code on several function calls. For instance, you need to measure the time elapsed in code blocks, then Elixir macros will run for help.

defmodule TimeFrame do
defmacro execute(name, units \\ :micro_seconds, do: yield) do
quote do
start = System.monotonic_time(unquote(units))
result = unquote(yield)
time_spent = System.monotonic_time(unquote(units)) - start
IO.puts("Executed #{unquote(name)} in #{time_spent} #{unquote(units)}")
result
end
end
end

Let’s run a piece of code and print automatically how much time was spent.

require TimeFrameresult1 = 
TimeFrame.execute "ti1" do
3 + 5 * 912312313123
end
# Executed ti1 in 5 micro_seconds
# 4561561565618
result2 =
TimeFrame.execute "ti2", :seconds do
IO.puts("sth")
3 + 5
end
# sth
# Executed ti2 in 0 seconds
# 8

In case, you need to use the result of executions; ‘result1’ will be assigned to value ‘4561561565618’ and ‘result2’ will be assigned to value ‘8’.

Lastly, if you don’t want to use always ‘unquote’ to access vars inside quote block, you can use ‘bind_quoted’.

Happy coding with ❤!

--

--

Mustafa Turan
ElixirLabs

Go, Elixir, Ruby, Software Architecture, Microservices