Project

General

Profile

Feature #2561 » rational_performance.rb

kstephens (Kurt Stephens), 01/06/2010 10:58 AM

 
require 'benchmark'

require 'rational'

$result = nil

$tests = <<END
#=begin
Rational(1, 2) + Rational(3, 4)
Rational(1, 2) + 10
Rational(1, 3) + 10.6
#=end

Rational(1, 2) - Rational(3, 4)
Rational(1, 2) - 10
Rational(1, 3) - 10.6
#=begin
Rational(1, 2) * Rational(3, 4)
Rational(1, 2) * 10
Rational(1, 3) * 10.6

Rational(1, 2) / Rational(3, 4)
Rational(1, 2) / 10
Rational(1, 3) / 10.6

Rational(1, 2) ** Rational(3, 4)
Rational(1, 2) ** 10
Rational(1, 2) ** -10
Rational(1, 2) ** 0
Rational(1, 3) ** 10.6

Rational(1, 2) == Rational(3, 4)
Rational(1, 2) == 10
Rational(1, 3) == 10.6

Rational(1, 2) <=> Rational(3, 4)
Rational(1, 2) <=> 10
Rational(1, 3) <=> 10.6

- Rational(1, 2)
- Rational(-1, 3)
- Rational(1, 4)

Rational(1, 2).abs
Rational(-1, 3).abs
Rational(1, 4).abs

Rational(1, 2).zero?
Rational(0, 2).zero?

Rational(1, 2).nonzero?
Rational(0, 2).nonzero?

#=end
#=begin
Rational(3, 4).to_s
Rational(5, 6).inspect
#=end

END

if ARGV.include?('--validate')
n = 1
instance_eval($expr = <<"END", __FILE__, __LINE__)
def test_it
result = [
#{$tests.split("\n").reject{|x| x =~ /^\s*$/}.join(",\n")}
]

if $result
unless result == $result
pp result
pp $result
raise "Assertion failed"
end
else
$result = result
end
end
END
else
n = 100000
n /= 2
instance_eval($expr = <<"END", __FILE__, __LINE__)
def test_it
#{$tests}
end
END
end
$stderr.puts $expr


Benchmark.bm(40) do | bm |

1.times do
ObjectSpace.garbage_collect
bm.report("test_it") do
n.times do
test_it
end
end
end

######################################################################

if (require('ks_rational') rescue nil)
ObjectSpace.garbage_collect
bm.report("test_it ks_rational") do
n.times do
test_it
end
end
end
end

(1-1/8)