【问题标题】:How to measure background activerecord model performance in rails?如何测量rails中的后台activerecord模型性能?
【发布时间】:2014-11-16 03:55:16
【问题描述】:

我的一个模型中似乎有一个非常慢的方法,我正在学习如何修复它。随之而来的是有效地对其进行基准测试,我认为我目前做得不是很好。

模型在 sidekiq 的后台运行,根据关键字处理锚文本以查找匹配项。我一直在使用 MethodProfiler gem 和时间戳来缩小我的get_top_match 方法的速度。我的代码如下所示:

# This is the code I'm running in the background
def spam_check
  words.each do |word|
    spam_keyword = SpamKeyword.top_match_for(word)
    spam_keyword.spam_score
  end
end

class SpamKeyword

def self.top_match_for(anchor_text)
    all_keywords_set.find do |keyword|
        if Regexp.new(keyword.keyword) =~ anchor_text
            if keyword.only_match_whole_words
                if /#{keyword.keyword}\b/ =~ anchor_text || /#{keyword.keyword.pluralize}\b/ =~ anchor_text
                    return keyword
                end
            else
                return keyword
            end
        end
    end
end

def self.all_keywords_set
    order(spam_score: :desc)
end

#The ways I've found to benchmark so far:`

MethodProfiler results for: SpamKeyword
+-------------------+------------+--------------+--------------+-----------------+-------------+
| Method            | Min Time   | Max Time     | Average Time | Total Time      | Total Calls |
+-------------------+------------+--------------+--------------+-----------------+-------------+
| .top_match_for    | 100.142 ms | 11406.057 ms | 2854.346 ms  | 19657882.947 ms | 6887        |
| .all_keywords_set | 0.056 ms   | 1318.212 ms  | 1.762 ms     | 12159.412 ms    | 6899        |
+-------------------+------------+--------------+--------------+-----------------+-------------+

spam_check_time 1273.384929213
    num_words_processed 222
    secs_per_word 5.735968149608109

我希望有更多关于如何提高性能的提示,但我认为最有用的可能是对这个问题的未来读者有用的,是查看堆栈跟踪的最佳方法是什么和数据库调用这样的后台方法?

【问题讨论】:

    标签: ruby-on-rails activerecord benchmarking performance-testing sidekiq


    【解决方案1】:

    我认为这里最好的工具是ruby-prof

    它可以显示每个方法花费的总时间。此外,它还会显示哪些方法调用了当前方法以及它调用了哪些方法。 Here is example output with comments.

    【讨论】:

      【解决方案2】:

      基本上今天,最相关的性能测量工具是benchmark-ips,你一定要使用它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-05
        • 2017-07-18
        相关资源
        最近更新 更多