Explain Codes LogoExplain Codes Logo

How to get execution time in rails console?

ruby
benchmarking
performance-tuning
rails-console
Alex KataevbyAlex Kataev·Nov 14, 2024
TLDR

If you're after a quick method to analyze execution time in Rails, the Benchmark.measure method is your best bet. Wrap your Rails code within its block, and voila, you have your performance stats in no time.

# No magic allowed, just good old-fashioned ruby require 'benchmark' puts Benchmark.measure { User.all }

This outputs the time it took to fetch all User records in an easy-to-digest format.

Understanding Benchmark.measure

When you execute your code, Benchmark.measure returns a Benchmark::Tms object, which offers comprehensive metrics, including the all-important CPU time. It's like getting back a detailed report card on your code's performance!

Making sense of Benchmark::Tms

In the world of benchmarks, Benchmark::Tms is the key holder. The output from this is typically in the following format:

user system total real 1.200000 0.000000 1.200000 ( 1.231074)

In this output, 'user' is the CPU time in user-mode, 'system' is system-mode, the 'total' is the sum of both, and 'real' represents the total elapsed real-time. Now isn't that handy?

Going deeper: Iteration Performance

Sometimes you want to know more - how does your code perform on an iterative basis? Or how does alternate processes stack up against each other? The benchmark-ips gem can help with this and provide an iterative performance comparison.

# Loading required gem equivalent to taking your protein before a workout! require 'benchmark/ips' Benchmark.ips do |x| # Oh look, queries are having a race! x.report("find_each") { User.find_each { |user| user } } x.report("all.each") { User.all.each { |user| user } } x.compare! end

If you're looking for more in-depth insights, such as memory allocation, using the execution_time gem might be your picnic.

Quick visual splashes with MiniProfiler

Some devs prefer a go-green, aesthetic approach to their consoles. rack-mini-profiler is the perfect tool to add a stopwatch to your development pages, providing direct execution time of your database calls.

Log'em all - ActiveRecord Logger

Being a savvy developer involves taking advantage of available tools. One such tool is ActiveRecord::Base.logger. It enables you to inspect SQL execution times right in your Rails server log file or console.

# Logger - for times when you want SQL to talk back to you! ActiveRecord::Base.logger = Logger.new(STDOUT) User.all