Skip to content

Instantly share code, notes, and snippets.

@panmari
Last active May 11, 2018 10:59
Show Gist options
  • Save panmari/73a2c203d24e7e9461d1 to your computer and use it in GitHub Desktop.
Save panmari/73a2c203d24e7e9461d1 to your computer and use it in GitHub Desktop.
Benchmark of various methods to retrieve a random record from a table using ActiveRecord and a Postgresql db behind.
require 'benchmark'
# Disable logging if in development/test mode
ActiveRecord::Base.logger = nil
model_name = Icd
N = 100
Benchmark.bm(11) do |x|
x.report('ruby rand') { N.times { model_name.offset(rand(model_name.count)).first } }
x.report('psql RANDOM') { N.times { model_name.order('RANDOM()').first } }
end
@panmari
Copy link
Author

panmari commented Jan 11, 2015

For a fairly large table with 131883 rows, I got these timings:

                  user     system      total        real
ruby rand     0.320000   0.020000   0.340000 (  6.786860)
psql RANDOM   0.210000   0.010000   0.220000 ( 17.870080)

using Rails 4.2, Postgresql 9.4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment