【发布时间】: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