Module: NA::Benchmark

Defined in:
lib/na/benchmark.rb,
lib/na.rb

Overview

Provides benchmarking utilities for measuring code execution time.

Examples:

Measure a block of code

NA::Benchmark.measure('sleep') { sleep(1) }

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.enabledObject

Returns the value of attribute enabled.



10
11
12
# File 'lib/na/benchmark.rb', line 10

def enabled
  @enabled
end

.timingsObject

Returns the value of attribute timings.



10
11
12
# File 'lib/na/benchmark.rb', line 10

def timings
  @timings
end

Class Method Details

.initvoid

This method returns an undefined value.

Initialize benchmarking state



15
16
17
18
19
# File 'lib/na/benchmark.rb', line 15

def init
  @enabled = %w[1 true].include?(ENV.fetch('NA_BENCHMARK', nil))
  @timings = []
  @start_time = Time.now
end

.measure(label) ⇒ Object

Measure the execution time of a block

Examples:

NA::Benchmark.measure('sleep') { sleep(1) }

Parameters:

  • label (String)

    Label for the measurement

Returns:

  • (Object)

    Result of the block



27
28
29
# File 'lib/na/benchmark.rb', line 27

def self.measure(_label)
  yield
end

.reportvoid

This method returns an undefined value.

Output a performance report to STDERR

Examples:

NA::Benchmark.report


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/na/benchmark.rb', line 42

def report
  return unless @enabled

  total = @timings.sum { |t| t[:duration] }
  warn "\n#{NA::Color.template('{y}=== NA Performance Report ===')}"
  warn NA::Color.template("{dw}Total: {bw}#{total.round(2)}ms{x}")
  warn NA::Color.template("{dw}GC Count: {bw}#{GC.count}{x}") if defined?(GC)
  if defined?(GC)
    warn NA::Color.template("{dw}Memory: {bw}#{(GC.stat[:heap_live_slots] * 40 / 1024.0).round(1)}KB{x}")
  end
  warn ''

  @timings.each do |timing|
    pct = total.positive? ? ((timing[:duration] / total) * 100).round(1) : 0
    bar = '█' * [(pct / 2).round, 50].min
    warn NA::Color.template(
      "{dw}[{y}#{bar.ljust(25)}{dw}] {bw}#{timing[:duration].to_s.rjust(7)}ms {dw}(#{pct.to_s.rjust(5)}%) {x}#{timing[:label]}"
    )
  end
  warn NA::Color.template("{y}#{'=' * 50}{x}\n")
end