我的一个模型中似乎有一个非常慢的方法,我正在学习如何修复它。随之而来的是它的有效基准,我不认为我现在做得很好。
该模型在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
我喜欢关于如何提高性能的更多提示,但我认为可能最有用的东西,对这个问题的未来读者有用,是什么是最好的方法查看这些背景方法的堆栈跟踪和数据库调用?
答案 0 :(得分:1)
我认为这里最好的工具是ruby-prof。
它可以显示每种方法花费的总时间。此外,它还将显示哪些方法调用当前方法以及调用哪些方法。 Here is example output with comments
答案 1 :(得分:0)
基本上今天,最相关的绩效衡量工具是benchmark-ips,你绝对应该使用它。