Ruby - 为什么这个次要的函数更改会导致很大的时间差异?

时间:2016-02-25 19:50:51

标签: ruby performance

此脚本适用于Project Euler #14

我正在重构它,我所做的只是抓取1行代码n.even? ? n = n/2 : n = (3*n) + 1并将其置于自己的函数中。此更改会将执行时间增加5秒。

为什么会这样?

在:

def longest_collatz_sequence1(count)
  check = []
  while count >= 1
    n = count
    seq = [count]
    while n > 1
      n.even? ? n = n/2 : n = (3*n) + 1
      seq << n
    end
    count -= 1
    check << seq
    value = sequence_check(check) if check.length == 2
  end
  puts "The number that produces the largest chain is: #{value[0][0]}"
end

def sequence_check(check)
  check[0].length > check[1].length ? check.delete_at(1) : check.delete_at(0)
  check
end

s = Time.new
longest_collatz_sequence1 1000000
puts "elapsed: #{Time.new-s}"
#~12.2 seconds

后:

def longest_collatz_sequence1(count)
  check = []
  while count >= 1
    n = count
    seq = [count]
    while n > 1
      n=collatz(n)
      seq << n
    end
    count -= 1
    check << seq
    value = sequence_check(check) if check.length == 2
  end
  puts "The number that produces the largest chain is: #{value[0][0]}"
end

def collatz(n)
  n.even? ? n = n/2 : n = (3*n) + 1
end
def sequence_check(check)
  check[0].length > check[1].length ? check.delete_at(1) : check.delete_at(0)
  check
end

s = Time.new
longest_collatz_sequence1 1000000
puts "elapsed: #{Time.new-s}"
#~17.7 seconds

0 个答案:

没有答案