How to get execution time in rails console?
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.
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:
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.
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.
Was this article helpful?