Rails has added a benchmark generator

1 minute read

Rails added a new benchmark generator. This is used to create benchmark file that uses benchmark-ips.

To use the benchmark generator, run

rails generate benchmark my_benchmark

This creates a benchmark file script/benchmarks/my_benchmark.rb . It also adds benchmark-ips gem to Gemfile. Be default, it adds 2 blocks for reporting before and after that can be used for benchmarking.

The file content looks like following:

# frozen_string_literal: true require_relative "../../config/environment" # Any benchmarking setup goes here... Benchmark.ips do |x| x.report("before") { } x.report("after") { } x.compare! end

This benchmark can be run using following command:

ruby script/benchmarks/my_benchmark.rb

Since we load config/environment.rb file, the Rails application environment is available to us in the script. The script runs in development environment.

We can pass different reports to add to benchmark as arguments to generate command as follows:

rails generate benchmark my_benchmark_2 report1 report2 report3

This will generate benchmark file as following:

# frozen_string_literal: true require_relative "../config/environment" # Any benchmarking setup goes here... Benchmark.ips do |x| x.report("report1") { } x.report("report2") { } x.report("report3") { } x.compare! end

The main purpose of adding the generator is it provides a convenient way to setup and perform benchmarks using the benchmark-ips gem.