【问题标题】:How to determine the cause of a delay before an action is hit in my Rails app?如何在我的 Rails 应用程序中执行操作之前确定延迟的原因?
【发布时间】:2021-01-30 03:06:41
【问题描述】:

我的故障排除陷入了死胡同,我真的希望有人能提供帮助。

我正在使用 rack-mini-profiler 来帮助定位我的 Rails 网站中的潜在内存泄漏。我将其范围缩小到正在调用的方法。

高层简介:rack-mini-profiler high-level

SQL 配置文件:rack-mini-profiler results

在 SQL 配置文件图片中,请注意灰色条上方和下方的查询开始时间相差 1037 毫秒。这是我注意到的延迟,它会一直增长,直到我重新启动应用程序。

在本地运行时,我可以监控终端。当请求该方法时,只有 1 秒的延迟,然后它就会执行。在此延迟期间,终端中不会显示任何查询或命令。

是否有人对我如何找出造成这种延迟的原因有任何想法?

我正在使用 Ruby 2.2.0 和 Rails 4.1.6。

谢谢!!

编辑:

这是 rack-mini-profiler 指向的方法:

def submit_answer
    quiz_attempt = CourseCompletion.find_by_id(params[:course_completion_id]).quiz_started
    choice = Choice.new(:answer_id => params[:answer], :quiz_attempt_id => quiz_attempt.id)
    @success = choice.save
    @answer = choice.answer
    @question = @answer.question
    @quiz_attempt = choice.quiz_attempt
    render :layout => false
  end

【问题讨论】:

标签: ruby-on-rails ruby memory-leaks rack-mini-profiler


【解决方案1】:

看看 ruby​​-prof github.com/ruby-prof/ruby-prof。尝试将您的操作主体包装到块中:

require 'ruby-prof'

# profile the code
RubyProf.start
# ... code to profile ...
result = RubyProf.stop

# print a flat profile to text
printer = RubyProf::FlatPrinter.new(result)
printer.print(STDOUT)

您应该会在控制台中收到如下输出:

您还可以将分析器的输出重定向到日志或服务器上的某个文件。

所以在你的情况下编辑代码:

def submit_answer
    require 'ruby-prof'
    # profile the code
    RubyProf.start


    quiz_attempt = CourseCompletion.find_by_id(params[:course_completion_id]).quiz_started
    choice = Choice.new(:answer_id => params[:answer], :quiz_attempt_id => quiz_attempt.id)
    @success = choice.save
    @answer = choice.answer
    @question = @answer.question
    @quiz_attempt = choice.quiz_attempt
    render :layout => false

    result = RubyProf.stop
    # print a flat profile to text
    printer = RubyProf::FlatPrinter.new(result)
    printer.print(STDOUT)
  end

添加到 gemfile

gem 'ruby-prof'

运行bundle install 并重新启动服务器。尝试再次运行操作并检查 rails 控制台输出。表格顶部的方法最耗时。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 2015-05-17
    • 2022-07-22
    相关资源
    最近更新 更多