我创建了一个用于选择用户的算法,它的运行速度比我想要的要慢,因为它被用于无限滚动网页。
我对 Ruby 的了解还不够,无法确定可以提高效率的方法。有没有人有任何想法?
def gen_users(list_length)
new_selection = []
# get all users
all_users = User.all
# shuffle them randomly
shuffled_users = all_users.shuffle
# cycle through all users randomly
shuffled_users.each do |user|
# check user profile isn't already in current selection
if !@users.include?(user)
# check user profile exists
if user.etkh_profile
profile_completeness = user.etkh_profile.get_profile_completeness
# check user profile meets minimum requirements
if profile_completeness >= MIN_PROFILE_COMPLETENESS && user.avatar? \
&& user.etkh_profile.background.length >= MIN_BACKGROUND_LENGTH
# insert randomness and bias towards profiles with high completeness
r = Random.new
rand = r.rand(1..10) # random integer between 1 and 10
product = rand * profile_completeness
# threshold is defined by the probability that a profile with min profile completeness
# will be selected
max_product = MIN_PROFILE_COMPLETENESS * 10
threshold = (1 - PROBABILITY_MIN_PROFILE) * max_product
if product >= threshold
# add to total list
@users << user
# add to list of latest selection
new_selection << user
end
end
end
end
# exit loop if enough users have been found
break if new_selection.length >= list_length
end
# return this selection
return new_selection
end