🎓 A1Learner
🔍
0 of 46 lessons completed

Elixir Counters and Profiling

Counters are fast shared tallies that a process updates without sending messages. Profiling with counters means recording how often each kind of event happens.

Tallies hold values you set and add

One tally is set to ten. Another tally gains five.

ref = :counters.new(2, [])
:counters.put(ref, 1, 10)
:counters.add(ref, 2, 5)
IO.inspect(:counters.get(ref, 1))
IO.inspect(:counters.get(ref, 2))

Tallies can go up and down

A tally starts at ten, gains three, then loses four. The final tally is nine.

ref = :counters.new(1, [])
:counters.put(ref, 1, 10)
:counters.add(ref, 1, 3)
:counters.sub(ref, 1, 4)
IO.inspect(:counters.get(ref, 1))

Separate tallies profile separate events

Hits and misses are counted in different tallies. The totals show two hits and one miss.

ref = :counters.new(2, [])
:counters.add(ref, 1, 1)
:counters.add(ref, 1, 1)
:counters.add(ref, 2, 1)
IO.inspect(:counters.get(ref, 1))
IO.inspect(:counters.get(ref, 2))

Example

ref = :counters.new(2, [])
Enum.each([:hit, :miss, :hit, :hit, :miss], fn outcome ->
  case outcome do
    :hit -> :counters.add(ref, 1, 1)
    :miss -> :counters.add(ref, 2, 1)
  end
end)
IO.inspect(:counters.get(ref, 1))
IO.inspect(:counters.get(ref, 2))

Key points

  • Counter set: :counters.new creates a set of numbered tallies.
  • Add: :counters.add increases one tally by a given amount.
  • Get: :counters.get reads one tally without changing it.
  • Put: :counters.put sets one tally to an exact value.
  • Subtract: :counters.sub decreases one tally by a given amount.
  • Use a separate tally for each event kind, then read the totals at the end.

In this example, a two-tally set is created, then a fixed list of five outcomes is walked, then each hit adds to the first tally and each miss adds to the second tally, and finally both totals are printed.

Note

a tally starts at zero unless it is set to another value.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A tally is set to 10, then 3 is added and 4 is subtracted. What does get return?