Module: Rperf::Text

Defined in:
lib/rperf.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, header: true) ⇒ Object



1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
# File 'lib/rperf.rb', line 1232

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

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

  result = Rperf.send(:compute_flat_cum, samples_raw)

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

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



1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
# File 'lib/rperf.rb', line 1255

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
    pct = total_weight > 0 ? weight * 100.0 / total_weight : 0.0
    loc = path.empty? ? "" : " (#{path})"
    out << format("  %14s ms %5.1f%%  %s%s\n", Rperf.send(:format_ms, weight), pct, label, loc)
  end
  out
end