Measuring Performance
Benchmark module.
Why Measure?
Optimizing without measuring is guessing. The Benchmark module in Ruby's standard library times code precisely.
- Find the slow parts before changing them
- Compare implementations objectively
- Avoid premature optimization
require 'benchmark'
time = Benchmark.realtime do
1_000_000.times { |i| i * 2 }
end
puts "Took #{time.round(4)}s"Benchmark.measure
Benchmark.measure returns a report of user, system, and real time.
- User time is CPU in your code
- Real time is wall clock elapsed
require 'benchmark'
result = Benchmark.measure do
500_000.times { |i| i.to_s }
end
puts resultAll lessons in this course
- Measuring Performance
- Profiling Tools
- Memory Optimization
- Common Bottlenecks