简体   繁体   English

Ruby on Rails的一些代码的优化

[英]Ruby on Rails optimalization of some code

I have some simple code that uses the minmax algoritm to locate birds. 我有一些使用minmax算法定位鸟类的简单代码。 Everything works but I find my programming not good and I believe there is a better solution. 一切正常,但我发现编程不好,我相信有更好的解决方案。 I'm not that experienced in RoR but if somebody knows a better way to achieve the same solution then I'm greatful ;). 我在RoR方面没有那么丰富的经验,但是如果有人知道实现相同解决方案的更好方法,那么我会很好;)。

There are two parts I hate, the 4 lists I had to create to determine the max or min value for the different combinations (the core of the min-max algorithm) and the very ugly SQL hack. 我讨厌两部分,我必须创建4个列表来确定不同组合的最大或最小值(最小-最大算法的核心)和非常丑陋的SQL hack。

Thanks! 谢谢!

 def index
# fetch all our birds
@birds = Bird.all
# Loop over the birds
@birds.each do |bird|
  @fixed = Node.where("d7type = 'f'")
  xminmax = []
  xmaxmin = []
  yminmax = []
  ymaxmin = []
  @fixed.each do |fixed|
    rss = Log.find_by_sql("SELECT logs.fixed_mac, AVG(logs.blinker_rss) AS avg_rss FROM logs
              WHERE logs.blinker_mac = '#{bird.d7_mac}' AND logs.fixed_mac = '#{fixed.d7_mac}' ORDER BY logs.id DESC LIMIT 30")
    converted_rss = calculate_distance_rss(rss[0].attributes["avg_rss"])
    xminmax.push(fixed.xpos + converted_rss)
    xmaxmin.push(fixed.xpos - converted_rss)
    yminmax.push(fixed.ypos + converted_rss)
    ymaxmin.push(fixed.ypos - converted_rss)
  end

  pos = {x: (xminmax.min + xmaxmin.max) / 2, y: (yminmax.min + ymaxmin.max) / 2}
  puts pos


end

end 结束

2 things you could do to start with is (assuming Birds could be a large table) Change Bird.all to 您可以从两件事开始(假设Birds可能是一张大桌子),将Bird.all更改为

Bird.find_each do |bird|
  ... code ...
end

It's a more efficient way to loop over many table records. 这是循环许多表记录的更有效方法。

2nd: take @fixed = Node.where("d7type = 'f'") out of the each loop since it doesn't need any variables for its query. 第二:将@fixed = Node.where("d7type = 'f'")从每个循环中删除,因为它不需要任何变量来进行查询。 Put it above the loop so it doesn't execute each time. 将其放在循环上方,这样就不会每次都执行。

3rd (Not so much of an optimization but just safer code): Your Log.find_by_sql looks simple enough to use active_record, you can change it to: 第三(不是最优化,而是更安全的代码):您的Log.find_by_sql看起来足够简单,可以使用active_record,可以将其更改为:

Log.select('fixed_mac, AVG(logs.blinker_rss) AS avg_rss, blinker_mac').
    where(blinker_mac: bird.d7_mac, fixed_mac: fixed.d7_mac).
    order('id DESC').limit(30)

converted_rss = calculate_distance_rss(rss.first.avg_rss)

Everything else looks fine. 其他一切看起来都很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM