Development Tip

Ruby 메서드의 시간 측정 및 벤치 마크

yourdevel 2020. 10. 22. 22:58
반응형

Ruby 메서드의 시간 측정 및 벤치 마크


Ruby에서 메서드와 해당 메서드의 개별 문에 걸리는 시간을 어떻게 측정 할 수 있습니까? 아래 방법을 보면 방법에 걸린 총 시간과 데이터베이스 액세스 및 redis 액세스에 걸린 시간을 측정하고 싶습니다. 모든 문 앞에 Benchmark.measure를 작성하고 싶지 않습니다. 루비 인터프리터가이 작업을 수행 할 수있는 방법을 제공합니까?

def foo
# code to access database
# code to access redis. 
end

Time개체를 사용할 수 있습니다 . ( 타임 문서 )

예를 들면

start = Time.now
# code to time
finish = Time.now

diff = finish - start

diff 부동 소수점 숫자로 초 단위입니다.

편집 : end예약되어 있습니다.


가장 간단한 방법 :

require 'benchmark'

def foo
 time = Benchmark.measure {
  code to test
 }
 puts time.real #or save it to logs
end

샘플 출력 :

2.2.3 :001 > foo
  5.230000   0.020000   5.250000 (  5.274806)

값은 CPU 시간, 시스템 시간, 총 및 실제 경과 시간입니다.

출처 : 루비 문서 .


벤치 마크 보고서 사용

require 'benchmark' # Might be necessary.

def foo
  Benchmark.bm(20) do |bm|  # The 20 is the width of the first column in the output.
    bm.report("Access Database:") do 
      # Code to access database.
    end

    bm.report("Access Redis:") do
      # Code to access redis.
    end
  end
end

그러면 다음과 같은 결과가 출력됩니다.

                        user     system      total        real
Access Database:    0.020000   0.000000   0.020000 (  0.475375)
Access Redis:       0.000000   0.000000   0.000000 (  0.000037)

<------ 20 ------->  # This is where the 20 comes in. NOTE: Not shown in output.

자세한 내용은 여기 에서 확인할 수 있습니다 .


두 번째 로 Ruby 코드 블록 인수로 measure () 함수를 정의 하면 시간 측정 코드를 단순화하는 데 도움이 될 수 있습니다.

def measure(&block)
  start = Time.now
  block.call
  Time.now - start
end

# t1 and t2 is the executing time for the code blocks.
t1 = measure { sleep(1) }

t2 = measure do
  sleep(2)
end

많은 답변에서 Time.now. 그러나 그것이 Time.now바뀔 수 있다는 것을 아는 것은 가치가 있습니다. 시스템 시계는 드리프트 될 수 있으며 시스템 관리자 또는 NTP를 통해 수정할 수 있습니다. 따라서 Time.now가 앞뒤로 이동하여 벤치마킹 결과가 정확하지 않을 수 있습니다.

더 나은 해결책은 항상 앞으로 나아가는 운영 체제의 단조로운 시계를 사용하는 것입니다. Ruby 2.1 이상에서는 다음을 통해 액세스 할 수 있습니다.

start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
# code to time
finish = Process.clock_gettime(Process::CLOCK_MONOTONIC)
diff = finish - start # gets time is seconds as a float

여기에서 자세한 내용을 읽을 수 있습니다 . 또한 인기있는 Ruby 프로젝트 인 Sidekiq이 단조 시계로 전환 한 것을 볼 수 있습니다 .


Look into the ruby-prof package, it should have what you need. It will create huge call stacks with timings.

http://ruby-prof.rubyforge.org/

It might be too granular, in which case just wrapping bigger sections in Benchmark.measure might be a good way to go.


In the spirit of wquist's answer, but a little simpler, you could also do it like below:

start = Time.now
# code to time
Time.now - start

참고URL : https://stackoverflow.com/questions/11406410/measure-and-benchmark-time-for-ruby-methods

반응형