分析 rails 控制器操作 [英] Profile a rails controller action

查看:40
本文介绍了分析 rails 控制器操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby on Rails 中分析控制器操作的最佳方法是什么.目前,我正在使用蛮力方法,在我认为会成为瓶颈的地方之间插入 puts Time.now 调用.但那感觉真的,真的很脏.必须有更好的方法.

What is the best way to profile a controller action in Ruby on Rails. Currently I am using the brute-force method of throwing in puts Time.now calls between what I think will be a bottleneck. But that feels really, really dirty. There has got to be a better way.

推荐答案

我不久前学会了这项技术,发现它非常方便.

I picked up this technique a while back and have found it quite handy.

当它就位时,您可以将 ?profile=true 添加到访问控制器的任何 URL.您的操作将照常运行,但它不会将呈现的页面传送到浏览器,而是发送一个详细的、格式良好的 ruby​​-prof 页面,显示您的操作所花费的时间.

When it's in place, you can add ?profile=true to any URL that hits a controller. Your action will run as usual, but instead of delivering the rendered page to the browser, it'll send a detailed, nicely formatted ruby-prof page that shows where your action spent its time.

首先,将 ruby​​-prof 添加到您的 Gemfile 中,可能在开发组中:

First, add ruby-prof to your Gemfile, probably in the development group:

group :development do
    gem "ruby-prof"
end

然后将周围过滤器添加到您的应用控制器:

Then add an around filter to your ApplicationController:

around_action :performance_profile if Rails.env == 'development'

def performance_profile
  if params[:profile] && result = RubyProf.profile { yield }

    out = StringIO.new
    RubyProf::GraphHtmlPrinter.new(result).print out, :min_percent => 0
    self.response_body = out.string

  else
    yield
  end
end

阅读 ruby​​-prof 输出是一门艺术,但我将把它留作练习.

Reading the ruby-prof output is a bit of an art, but I'll leave that as an exercise.

ScottJShea 的补充说明:如果您想更改测量类型,请放置:

Additional note by ScottJShea: If you want to change the measurement type place this:

RubyProf.measure_mode = RubyProf::GC_TIME #example

在应用程序控制器的配置文件方法中的 if 之前.您可以在 ruby-prof 页面中找到可用测量的列表.在撰写本文时,memoryallocations 数据流似乎已损坏(查看缺陷).

Before the if in the profile method of the application controller. You can find a list of the available measurements at the ruby-prof page. As of this writing the memory and allocations data streams seem to be corrupted (see defect).

这篇关于分析 rails 控制器操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆