Module: Sperf::Text

Defined in:
lib/sperf.rb

Overview

Text report encoder — human/AI readable flat + cumulative top-N table.

Class Method Summary collapse

Class Method Details

.encode(data, top_n: 50) ⇒ Object



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/sperf.rb', line 381

def encode(data, top_n: 50)
  samples_raw = data[:samples]
  mode = data[:mode] || :cpu
  frequency = data[:frequency] || 0

  return "No samples recorded.\n" if !samples_raw || samples_raw.empty?

  flat = Hash.new(0)
  cum = Hash.new(0)
  total_weight = 0

  samples_raw.each do |frames, weight|
    total_weight += weight
    seen = {}

    frames.each_with_index do |frame, i|
      path, label = frame
      key = [label, path]
      flat[key] += weight if i == 0

      unless seen[key]
        cum[key] += weight
        seen[key] = true
      end
    end
  end

  out = String.new
  total_ms = total_weight / 1_000_000.0
  out << "Total: #{"%.1f" % total_ms}ms (#{mode})\n"
  out << "Samples: #{samples_raw.size}, Frequency: #{frequency}Hz\n"
  out << "\n"
  out << format_table("Flat", flat, total_weight, top_n)
  out << "\n"
  out << format_table("Cumulative", cum, total_weight, top_n)
  out
end

.format_table(title, table, total_weight, top_n) ⇒ Object



419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/sperf.rb', line 419

def format_table(title, table, total_weight, top_n)
  sorted = table.sort_by { |_, w| -w }.first(top_n)
  out = String.new
  out << "#{title}:\n"
  sorted.each do |key, weight|
    label, path = key
    ms = weight / 1_000_000.0
    pct = total_weight > 0 ? weight * 100.0 / total_weight : 0.0
    loc = path.empty? ? "" : " (#{path})"
    out << ("  %8.1fms %5.1f%%  %s%s\n" % [ms, pct, label, loc])
  end
  out
end