LoginSignup
4
1

More than 1 year has passed since last update.

Rails・Rubyで benchmark を使って簡単にパフォーマンス計測をしてみよう!

Last updated at Posted at 2022-09-14

はじめに

先輩や上司に、「どのロジックがパフォーマンス良いか調べてみて」と言われることはありませんか?
または、先輩や上司にコードを見せる前にどのロジックがパフォーマンス良いか調べたいことがありますよね。

Rails パフォーマンス計測 で検索すると、rack-mini-profilerのGemが出てくると思います。
ただ、実務においてGemを導入するのはハードルが高いです。

そこでRubyに標準であるbenchmarkを使ってみましょう。

benchmarkとは

ベンチマークの計測ができます。そのままですね。

こちらのbmメソッドを使用していきます。

サンプルコードは以下になります。

require 'benchmark'

n = 50000
Benchmark.bm do |x|
x.report { for i in 1..n; a = "1"; end }
x.report { n.times do   ; a = "1"; end }
x.report { 1.upto(n) do ; a = "1"; end }
end

#=>
#
#     user     system      total        real
# 1.033333   0.016667   1.016667 (  0.492106)
# 1.483333   0.000000   1.483333 (  0.694605)
# 1.516667   0.000000   1.516667 (  0.711077)

計測された user systemを見てあげればOKです。
以下はこちらの記事(https://zenn.dev/publiclocaldev/articles/63e0fb1eb098ce) の引用です。

user
ユーザー CPU 時間
ユーザープログラムの実行に費やした CPU 時間。この場合、Ruby スクリプトを実行すべく Ruby 処理系が働いたぶんの CPU 時間のこと。

system
システム CPU 時間
OS はファイルの読み書きなどの基本的な機能を「システムコール」という形で提供しているが、プログラムがそれを呼び出しその実行に費やした CPU 時間をこう呼ぶらしい。

実務のコードでパフォーマンス計測をする

「ユーザーがいいねしている記事を取得する」メソッドを実装しているとします。
Userモデルにロジックを2〜3種類書いてみて、どれがパフォーマンスが良いか計測するには、
下記のようにしてあげるとOKです。

users_controller.rb
 class UsersController < ApplicationController
    require 'benchmark'

    ...

    def index
      time = Benchmark.bm do |x|
        x.report("method1") { User.method1 }
        x.report("method2") { User.method2 }
        x.report("method3") { User.method3 }
      end
      logger.debug time
    end

    ...
 end

これでログにパフォーマンス計測の結果が出力されます!
出力した結果を分析してパフォーマンスが良いメソッド及びロジックを採用すると良いでしょう!

4
1
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
4
1