我創建了一個選擇用戶的算法,由於它在無盡滾動網頁上使用,所以運行速度比我想要的要慢。加速我的Ruby代碼
我不太瞭解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 [email protected]?(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
這樣的問題屬於http://codereview.stackexchange.com。有關更多信息,請參閱[常見問題](http://codereview.stackexchange.com/faq#im-confused-what-questions-are-on-topic-for-this-site)。 – 2013-02-24 17:25:03