0
0
Rubyprogramming~5 mins

Performance profiling basics in Ruby

Choose your learning style9 modes available
Introduction

Performance profiling helps you find which parts of your Ruby program take the most time. This way, you can make your program faster and better.

When your Ruby program feels slow and you want to know why.
Before optimizing code to focus on the slowest parts.
To compare performance before and after changes.
When you want to understand how your program uses time during execution.
Syntax
Ruby
require 'ruby-prof'
RubyProf.start
# code to profile
result = RubyProf.stop
printer = RubyProf::FlatPrinter.new(result)
printer.print(STDOUT)

You need to install the ruby-prof gem first using gem install ruby-prof.

The code between RubyProf.start and RubyProf.stop is what gets measured.

Examples
This example profiles a simple 1-second sleep to show how profiling works.
Ruby
require 'ruby-prof'
RubyProf.start
sleep(1) # simulate work
result = RubyProf.stop
printer = RubyProf::FlatPrinter.new(result)
printer.print(STDOUT)
This example profiles a loop doing calculations and prints a graph-style report.
Ruby
require 'ruby-prof'
RubyProf.start
10.times { (1..1000).map { |i| i * i } }
result = RubyProf.stop
printer = RubyProf::GraphPrinter.new(result)
printer.print(STDOUT)
Sample Program

This program measures how long it takes to calculate the sum of squares from 0 to 999. The flat report shows time spent in each method.

Ruby
require 'ruby-prof'

# Start profiling
RubyProf.start

# Code to profile: simple loop
sum = 0
1000.times do |i|
  sum += i * i
end

# Stop profiling
result = RubyProf.stop

# Print flat report to console
printer = RubyProf::FlatPrinter.new(result)
printer.print(STDOUT)
OutputSuccess
Important Notes

Profiling adds some overhead, so the program runs slower while profiling.

Use profiling only when you want to improve performance, not all the time.

Look for methods with high self time to find slow parts.

Summary

Performance profiling helps find slow parts of Ruby code.

Use ruby-prof gem to measure and report time spent.

Focus on methods with high self time to optimize your program.