Project

General

Profile

Actions

Misc #13209

open

fact.rb in ruby/sample variations

Added by jzakiya (Jabari Zakiya) about 7 years ago. Updated about 7 years ago.

Status:
Open
Assignee:
-
[ruby-core:79510]

Description

I was looking at some of the Sample files that come with Ruby and
saw the example for doing factorials. It's an old example that I
thought I could make simpler/faster. Below are the results.

Maybe upgrading to show the difference between coding idioms can
be instructive to newer Ruby programmers.

def fact(n)
  return 1 if n == 0
  f = 1
  n.downto(1) do |i|
    f *= i
  end
  return f
end

def fact1(n)
  return 1 if n | 1 == 1  # if n 0 or 1
  f = 2 
  n.downto(3) do |i|
    f *= i
  end
  return f
end

def fact2(n)
  return 1 if n | 1 == 1  # if n 0 or 1
  (2..n).reduce(:*)
end

require 'benchmark/ips'

Benchmark.ips do |x|
  x.report("original factorial") { fact  100 }
  x.report("modified factorial") { fact1 100 }
  x.report("enhanced factorial") { fact2 100 }
  x.compare!
end

Timings using ruby-2.4.0 on Linux 64-bit, on I7 cpu system.

2.4.0 :001 > load 'factversiontest.rb'
Warming up --------------------------------------
  original factorial     4.501k i/100ms
  modified factorial     4.594k i/100ms
  enhanced factorial     5.271k i/100ms
Calculating -------------------------------------
  original factorial     44.962k (± 4.2%) i/s -    225.050k in   5.015176s
  modified factorial     46.288k (± 3.2%) i/s -    234.294k in   5.066948s
  enhanced factorial     53.425k (± 3.1%) i/s -    268.821k in   5.036635s

Comparison:
  enhanced factorial:    53424.9 i/s
  modified factorial:    46288.0 i/s - 1.15x  slower
  original factorial:    44961.5 i/s - 1.19x  slower

 => true 
2.4.0 :002 > 

Actions

Also available in: Atom PDF

Like0
Like0Like0