public
Last active

Code examples about "prior knowledge"

  • Download Gist
test-01.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#!/bin/ruby
 
require 'benchmark'
 
def sin radians
h = Hash.new(Math.sin(radians))
h[0.0] = 0
h[90.0] = 1
h[180.0] = 0
h[270.0] = -1
degrees = (radians / Math::PI * 180) % 360 # think in degrees for ease
h[degrees]
end
 
def sin2 x
rad = (x / Math::PI * 180) % 360 # think in degrees for ease
case rad
when 0; 0
when 90; 1
when 180; 0
when 270; -1
else Math.sin(x)
end
end
 
REPEAT = 1_000_000
 
Benchmark.bmbm 20 do |x|
x.report "Math.sin(0)" do
REPEAT.times { Math.sin(0) }
end
 
x.report "Math.sin(0.0)" do
REPEAT.times { Math.sin(0.0) }
end
 
x.report "sin(0)" do
REPEAT.times { sin(0) }
end
 
x.report "sin(0.0)" do
REPEAT.times { sin(0.0) }
end
 
x.report "sin2(0)" do
REPEAT.times { sin2(0) }
end
 
x.report "sin2(0.0)" do
REPEAT.times { sin2(0.0) }
end
 
end
test-02.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
 
require 'benchmark'
 
def fib1(n)
case n
when 0 then 0
when 1 then 1
else fib1(n-1) + fib1(n-2)
end
end
 
def fib2(n)
case n
when 0 then 0
when 1 then 1
else
f0 = 0
f1 = 1
 
for i in 2..n
f0, f1 = f1, f0 + f1
end
 
f1
end
end
 
fib3 = Hash.new do |h, n|
last = nil
 
for i in 2..n
h[i] = last = h[i - 1] + h[i - 2]
end
 
last
end.update(0 => 0, 1 => 1)
 
fib4 = Hash.new do |h, n|
last = nil
 
(h.m + 1).upto n do |i|
h[i] = last = h[i - 1] + h[i - 2]
end
 
h.m = n # we know n > h.m
last
end.update(0 => 0, 1 => 1)
 
class <<fib4
attr_accessor :m
end
 
fib4.instance_variable_set '@m', 1
 
10.times do |n|
f1 = fib1 n
f2 = fib2 n
f3 = fib3[n]
f4 = fib4[n]
 
printf "%10d %10d %10d %10d\n", f1, f2, f3, f4 unless f1 == f2 && f2 == f3 && f2 == f4
end
 
REPEAT = 100_000
 
Benchmark.bm 20 do |x|
x.report "fib1" do
REPEAT.times { fib1 10 }
end
 
x.report "fib2" do
REPEAT.times { fib2 10 }
end
 
x.report "fib3" do
REPEAT.times { fib3[10] }
end
 
x.report "fib4" do
REPEAT.times { fib4[10] }
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.