class Aggregate
Aggregates memory allocations by a given metric. Groups allocations and tracks totals for memory usage and allocation counts.
Definitions
def initialize(title, &block)
Initialize a new aggregate with a title and metric block.
Signature
-
parameter
titleString The title for this aggregate.
-
parameter
blockBlock A block that extracts the metric from an allocation.
Implementation
def initialize(title, &block)
@title = title
@metric = block
@total = Usage.new
@totals = Hash.new{|h,k| h[k] = Usage.new}
end
def <<(allocation)
Add an allocation to this aggregate.
Signature
-
parameter
allocationAllocation The allocation to add.
Implementation
def << allocation
metric = @metric.call(allocation)
total = @totals[metric]
total << allocation
@total << allocation
end
def totals_by(key)
Sort totals by a given key.
Signature
-
parameter
keySymbol The key to sort by (e.g., :size or :count).
-
returns
Array Sorted array of [metric, total] pairs.
Implementation
def totals_by(key)
@totals.sort_by{|metric, total| [total[key], metric]}
end
def print(io = $stderr, limit: 10, title: @title, level: 2)
Print this aggregate to an IO stream.
Signature
-
parameter
ioIO The output stream to write to.
-
parameter
limitInteger Maximum number of items to display.
-
parameter
titleString Optional title override.
-
parameter
levelInteger Markdown heading level for output.
Implementation
def print(io = $stderr, limit: 10, title: @title, level: 2)
io.puts "#{'#' * level} #{title} #{@total}", nil
totals_by(:size).last(limit).reverse_each do |metric, total|
io.puts "- #{total}\t#{metric}"
end
io.puts nil
end
def as_json(options = nil)
Convert this aggregate to a JSON-compatible hash.
Signature
-
parameter
optionsHash | Nil Optional JSON serialization options.
-
returns
Hash JSON-compatible representation.
Implementation
def as_json(options = nil)
{
title: @title,
total: @total.as_json(options),
totals: @totals.map{|k, v| [k, v.as_json(options)]}
}
end