MadsBoydMadsen

MadsBoydMadsen

Macro to provide timing for a function call - handle any signature

I’m working on a macro to support automatic timing for functions.
If I have this - say:

def double(x) do
  x + x
end

I would like to be able to change it to this on a needs basis:

def_timed double(x) do
  x + x
end

I’ve got the basics of a macro written that can handle this:

defmodule Cw.Utilities.Timing.DefTimed do
  defmacro def_timed({name, _meta, args} = _ast, do: body) do
    arg_vars = Enum.map(args, fn {arg_name, _, _} -> arg_name end)

    quote do
      def unquote(name)(unquote_splicing(args)) do
        Timer.wrap_timed(
          fn unquote_splicing(arg_vars) -> unquote(body) end,
          [unquote_splicing(arg_vars)],
          unquote(name)
        )
      end
    end
  end
end

defmodule Timer do
  def wrap_timed(fun, args, name) do
    start_time = System.monotonic_time(:millisecond)
    result = apply(fun, args)
    end_time = System.monotonic_time(:millisecond)

    IO.puts("""
    [TIMED] Function: #{name}
    [TIMED] Arguments: #{inspect(args)}
    [TIMED] Execution time: #{end_time - start_time} ms
    """)

    result
  end
end

This works fine for functions with simple signatures as above.
But it doesn’t work when the signatures includes keyword-list, optionals, guards or pattern-matching.

I sense, that this must be a solved problem, but I cannot find anything online to demonstrate how to do it.
I’m looking for help to work it out.

NOTE: One of my colleagues have just pointed out, that macros should only be used sparingly (Meta-programming anti-patterns — Elixir v1.18.2).
My use-case strikes me as being pretty perfect for a macro, as adding and removing instrumentation would be a breeze (good luck to me :smiley: )
Is there a better - and equally straight forward - way for me to achieve what I’m trying to do ?

Most Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Checkout Elixir function decorators — decorator v1.4.0 which implements a module attribute based decorator pattern.

The main code for defining decorators is here: decorator/lib/decorator/decorate.ex at master · arjan/decorator · GitHub

billylanchantin

billylanchantin

I’m honestly don’t think this is a solved problem largely for the reasons you note: the forms the AST can take are quite varied. While Elixir does give you the ability to manipulate AST directly, it doesn’t give you many nice helpers like Macro.find_the_do_block_in_this_ast/1.

(I’m speculating here, but I imagine it’s because the AST is an implementation detail subject to change.)

My personal experience with writing macros is that you’re on your own somewhat. The Meta-Programming chapters of the docs are quite good. But for specific applications, you often need to dig in and see what the expressions you plan to work with happen to come out as in AST form.

Note: another snag you’ll hit is that there are other blocks that come after the do block:

def reciprocal(x) when is_integer(x) do
  1 / x
rescue
  ArithmeticError -> :infinity
end
al2o3cr

al2o3cr

The tricky part is that a function doesn’t even need to name its arguments if it pattern-matches on them, for instance:

def foo([a | _], %{wat: b}) do
  ...
end

Replacing def with def_timed:

def_timed foo([a | _], %{wat: b}) do
  ...
end

could expand to something like:

def foo(arg1, arg2) do
  Timer.wrap_timed(
    &untimed_foo/2,
    [arg1, arg2],
    :foo
  )
end

def untimed_foo([a | _], %{wat: b}) do
  ...
end

untimed_foo would use the original args AST unaltered, while the code generated in foo only cares about length(args).

Supporting default args directly in def_timed would be a lot of extra hassle, but using a do-less def would let you avoid that:

def timed_thing_with_defaults(x, y \\ 1, z \\ 2)
def_timed timed_thing_with_defaults(x, y, z) do
  ...
end
garrison

garrison

Couldn’t you just re-use the function signature as-is and then wrap the body in an anonymous function and simply close over the arguments?

Like:

def double(x) do
  Timer.wrap_timed(fn ->
    x + x
  end)
end

BTW you should look into :timer.tc/1.

billylanchantin

billylanchantin

Just to clarify: I think the approach will work once you cover all the edge cases. I was mostly pushing back on this:

However I agree with @garrison. For most instances when I’ve needed to time functions, it was either for a one time thing or as part of a benchmarking effort.

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement