Class: Purplelight::Telemetry

Inherits:
Object
  • Object
show all
Defined in:
lib/purplelight/telemetry.rb

Overview

Lightweight, low-overhead timing and counters with a ticket API.

Constant Summary collapse

NULL =

A disabled singleton for zero overhead checks if needed.

new(enabled: false)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(enabled: true) ⇒ Telemetry

Returns a new instance of Telemetry.



6
7
8
9
10
# File 'lib/purplelight/telemetry.rb', line 6

def initialize(enabled: true)
  @enabled = enabled
  @counters = Hash.new(0)
  @timers = Hash.new(0.0)
end

Instance Attribute Details

#countersObject (readonly)

Returns the value of attribute counters.



45
46
47
# File 'lib/purplelight/telemetry.rb', line 45

def counters
  @counters
end

#timersObject (readonly)

Returns the value of attribute timers.



45
46
47
# File 'lib/purplelight/telemetry.rb', line 45

def timers
  @timers
end

Instance Method Details

#add(key, count = 1) ⇒ Object



31
32
33
34
35
# File 'lib/purplelight/telemetry.rb', line 31

def add(key, count = 1)
  return unless @enabled

  @counters[key] += count
end

#enabled?Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/purplelight/telemetry.rb', line 12

def enabled?
  @enabled
end

#finish(key, ticket) ⇒ Object

Finish a timer using a ticket from start. No-ops if ticket is nil.



24
25
26
27
28
29
# File 'lib/purplelight/telemetry.rb', line 24

def finish(key, ticket)
  return unless @enabled && ticket

  dt = Process.clock_gettime(Process::CLOCK_MONOTONIC) - ticket
  @timers[key] += dt
end

#merge!(other) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/purplelight/telemetry.rb', line 37

def merge!(other)
  return self unless @enabled

  other.counters.each { |k, v| @counters[k] += v }
  other.timers.each { |k, v| @timers[k] += v }
  self
end

#start(_key) ⇒ Object

Start a timer. Returns a ticket (Float) when enabled, or nil when disabled.



17
18
19
20
21
# File 'lib/purplelight/telemetry.rb', line 17

def start(_key)
  return nil unless @enabled

  Process.clock_gettime(Process::CLOCK_MONOTONIC)
end