MemorySourceMemory

module Memory

Memory profiler for Ruby applications. Provides tools to track and analyze memory allocations and retention.

Nested

Definitions

def self.formatted_bytes(bytes)

Format bytes into human-readable units.

Signature

parameter bytes Integer

The number of bytes to format.

returns String

Formatted string with appropriate unit (e.g., "1.50 MiB").

Implementation

def self.formatted_bytes(bytes)
	return "0 B" if bytes.zero?
	
	# Calculate how many times we can divide by 1024 (2^10)
	# log2(bytes) / 10 gives the number of 1024 divisions
	index = Math.log2(bytes).to_i / 10
	index = 8 if index > 8  # Cap at YiB
	
	# Divide by 1024^index, which equals 2^(index * 10)
	"%.2f #{UNITS[index]}" % (bytes / (1024.0 ** index))
end

def self.capture(report = nil, &block)

Capture memory allocations from a block of code.

Signature

parameter report Report | Nil

Optional report instance to add samples to.

parameter block Block

The code to profile.

returns Report

A report containing allocation statistics.

Implementation

def self.capture(report = nil, &block)
	sampler = Sampler.new
	sampler.run(&block)
	
	report ||= Report.general
	report.add(sampler)
	
	return report
end

def self.report(&block)

Generate a memory allocation report for a block of code.

Signature

parameter block Block

The code to profile.

returns Report

A report containing allocation statistics.

Implementation

def self.report(&block)
	self.capture(&block)
end