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)}")

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

require TimeFrameresult1 = 
TimeFrame.execute "ti1" do
3 + 5 * 912312313123
# Executed ti1 in 5 micro_seconds
# 4561561565618
result2 =
TimeFrame.execute "ti2", :seconds do
3 + 5
# 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 ❤!


Elixir, OTP, Phoenix Framework, Ecto

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store