小编Fra*_*air的帖子

Ruby的数字方法性能

我正在使用Ruby解决一些Project Euler问题,特别是在这里我说的是问题25(Fibonacci序列中包含1000位数的第一项的索引是什么?).

起初,我使用的是Ruby 2.2.3,我将问题编码为:

number = 3
a = 1
b = 2

while b.to_s.length < 1000
  a, b = b, a + b
  number += 1
end
puts number
Run Code Online (Sandbox Code Playgroud)

但后来我发现该版本2.4.2有一个方法digits,这正是我所需要的.我转换为代码:

while b.digits.length < 1000
Run Code Online (Sandbox Code Playgroud)

当我比较这两种方法时,digits速度要慢得多.

时间

./025/problem025.rb 0.13s user 0.02s system 80% cpu 0.190 total

./025/problem025.rb 2.19s user 0.03s system 97% cpu 2.275 total

有谁知道为什么?

ruby performance

5
推荐指数
1
解决办法
313
查看次数

标签 统计

performance ×1

ruby ×1