0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Array#sample と Random#rand ってどっちが速いんかな

Posted at

バッチ処理で数十万回ループしてその中で毎回ランダムな数を選びたい場合、Array#sampleRandom#rand でどっちがパフォーマンスがいいのか気になったので調べてみました。

さっそく以下計測

range = (1..10000)
array = range.to_a
num = 1000000

Benchmark.bm 10 do |r|
  r.report 'Array#sample' do
    num.times do
      array.sample
    end
  end

  r.report 'Random#rand' do
    num.times do
      rand(range)
    end
  end
end

結果は

                 user     system      total        real
Array#sample  0.114216   0.002376   0.116592 (  0.120891)
Random#rand  0.198875   0.001285   0.200160 (  0.206403)

というわけで Array#sample がわずかに速かったです。ただ今回 range を渡しているのでもしかしたら内部的に to_a とかしているせいかもしれない…

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?