Skip to content

Instantly share code, notes, and snippets.

@tompave
Last active August 20, 2016 15:44
Show Gist options
  • Save tompave/c1ffe3e144646d845e8b282496140750 to your computer and use it in GitHub Desktop.
Save tompave/c1ffe3e144646d845e8b282496140750 to your computer and use it in GitHub Desktop.
Fun with Elixir macros and Streams
defmodule Timing do
def now do
:os.system_time(:milli_seconds)
end
# broken! the block is executed immediately
#
def ftime([do: block]) do
t0 = now
{ :ok, block, now - t0 }
end
# ok. The block is "placed" where it is unquoted,
# and executed later
#
defmacro mtime([do: block]) do
quote do
t0 = Timing.now
{ :ok, unquote(block), Timing.now - t0 }
end
end
end
# ---------------------------
# Enum vs Stream
require Timing
{ :ok, result, ms } = Timing.mtime do
Enum.map(1..10_000_000, &(&1+1)) |> Enum.take(5)
end
# {:ok, [2, 3, 4, 5, 6], 14157}
{ :ok, result, ms } = Timing.mtime do
Stream.map(1..10_000_000, &(&1+1)) |> Enum.take(5)
end
# {:ok, [2, 3, 4, 5, 6], 1}
# Broken function implementation
{ :ok, result, ms } = Timing.ftime do
Enum.map(1..10_000_000, &(&1+1)) |> Enum.take(5)
end
# {:ok, [2, 3, 4, 5, 6], 0}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment