After understanding how macros work, we will now apply the insights we just got to see how we can create macros that add functionality to the caller module. Our objective here is to create a macro, ElixirDrip.Chronometer.defchrono/2, equivalent to the existing def/2 macro but with the additional feature that logs how long the function call took.
Let's start by looking at the end result. We want to be able to define functions such as defchrono fun_name(arg1, arg2), do: ... and when we call the fun_name/2 function, it will tell us Took 123 µs to run SomeModule.fun_name/2. The following MeasuredModule will be our research subject:
$ cat examples/measured_module.exs
defmodule MeasuredModule do
import ElixirDrip.Chronometer
defchrono_vn slow_times(x, y) do
Process.sleep(2000)
x * y
end
end
In the previous snippet, we are using the _vn suffix...