Skip to content

Instantly share code, notes, and snippets.

@danj3
Created March 26, 2018 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danj3/3a8613ccc5ae0d34786d26451acdee79 to your computer and use it in GitHub Desktop.
Save danj3/3a8613ccc5ae0d34786d26451acdee79 to your computer and use it in GitHub Desktop.
Elixir agent for active tracking execution time
defmodule TimeAgent do
def start_link do
Agent.start_link( fn -> { Map.new, Map.new } end, name: __MODULE__ )
end
def time_run( m, f, a ) do
{ us, result } = :timer.tc( m, f, a )
Agent.cast( __MODULE__, __MODULE__, :add_sample, [ to_string(m) <> "." <> to_string(f), us ] )
result
end
def time_run( name, fun ) do
{ us, result } = :timer.tc( fun )
Agent.cast( __MODULE__, __MODULE__, :add_sample, [ name, us ] )
result
end
def add_sample( { times, counts }, name, us ) do
{
Map.update( times, name, us, fn ous -> ous + us end ),
Map.update( counts, name, 1, fn oct -> oct + 1 end )
}
end
def status do
{ times, counts } = Agent.get( __MODULE__, fn state -> state end )
Enum.map( times, fn { name, time } ->
c = Map.get( counts, name )
aus = time / c
[
name: name,
count: c,
us: [
total: time,
avg: aus
],
s: [
total: time / 1000 / 1000,
avg: aus / 1000 / 1000
]
]
end)
end
def reset do
Agent.update( __MODULE__, fn _ -> { Map.new, Map.new } end )
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment