Implement a Basic block/yield with Elixir

Mustafa Turan
Feb 23, 2017 · 1 min read

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 ❤!

ElixirLabs

Elixir, OTP, Phoenix Framework, Ecto

Thanks to Omar Abdelhafith

Mustafa Turan

Written by

Go, Elixir, Ruby, Software Architecture, Microservices

ElixirLabs

Elixir, OTP, Phoenix Framework, Ecto

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade