ruby-on-rails - Rails 应用的性能分解

标签 ruby-on-rails performance

我有一个 Rails 模型,其中有许多方法相互调用,如下所示:

class MyModel
 def function1
 end
 ...
 def functionN
 end

 def summary
   function1
   ...
   functionN
 end

end

我想检查它调用的每个方法的摘要和分割运行时间的性能。我应该怎么做?

最佳答案

参见 Profile或者在 Ruby 中使用 -rprofile。以下是摘录:

Just require ‘profile’:

require 'profile'

def slow_method
  5000.times do
    9999999999999999*999999999
  end
end

def fast_method
  5000.times do
    9999999999999999+999999999
  end
end

slow_method fast_method

The output in both cases is a report when the execution is over:

ruby -rprofile example.rb

  %   cumulative   self              self     total  time   seconds  
seconds    calls  ms/call  ms/call  name
 68.42     0.13      0.13        2    65.00    95.00  Integer#times
 15.79     0.16      0.03     5000     0.01     0.01  Fixnum#*
 15.79     0.19      0.03     5000     0.01     0.01  Fixnum#+
  0.00     0.19      0.00        2     0.00     0.00  IO#set_encoding
  0.00     0.19      0.00        1     0.00   100.00  Object#slow_method
  0.00     0.19      0.00        2     0.00     0.00  Module#method_added
  0.00     0.19      0.00        1     0.00    90.00  Object#fast_method
  0.00     0.19      0.00        1     0.00   190.00  #toplevel

因此,您可以在代码中的某处添加 require 'profile'(但此后会显着降低处理速度),然后当 Rails 环境退出时,它将输出分析信息。对于您的示例,您可以在 Rails 控制台中执行。第一:

rails c

然后:

require 'profile'
MyModel.some_method_that_you_want_to_profile
exit

要过滤,可以这样做:

rails c 2>&1 | tee profile.txt

然后像上面那样测试,然后在你完成之后:

grep MyModel profile.txt

或者包含 header 并删除非分析输出:

grep -E "MyModel\#|cumulative   self|seconds    call" profile.txt

如果这太过分了,我建议 benchmark仅用于测试特定代码块或方法。

参见 performance testing在指南中了解更多信息。

另请查看 ruby-prof , 但不要长期将它留在你的 Gemfile 中——当它与其他一些 gem 一起使用时似乎有段错误).

Tracer , TracePoint (我认为现在是 Ruby 2 的一部分),autolog , set_trace_func等可能会帮助您了解正在调用的内容。

关于ruby-on-rails - Rails 应用的性能分解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16700045/

相关文章:

android - 适用于 Android 的预编译 FFmpeg 与使用 Android NDK 构建 FFmpeg

javascript - Ruby on Rails - jQuery 使用 AJAX 获取数据

mysql - ActiveRecord 范围查找今天创建的记录?

android - 如何在我的网络应用程序中使用来自 AccountManager 的 Google token ? (Rails with omniauth-google-oauth2)

ruby-on-rails - 为什么这个多态关联的 source_type 总是 0?

python - 我如何在 Django 中从 HTML 标签按钮在后台触发 Python 脚本?

sql - 将数据存储为数字和 double

javascript - Dropzone Rails 505 错误

.net - 更改数百个WinForms控件的位置的性能

c++ - C++ vs C源代码的编译和执行时间