Project

General

Profile

Feature #2561 ยป rational_performance.rb

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

 
1
require 'benchmark'
2

    
3
require 'rational'
4

    
5
$result = nil
6

    
7
$tests = <<END
8
#=begin
9
  Rational(1, 2) + Rational(3, 4)
10
  Rational(1, 2) + 10
11
  Rational(1, 3) + 10.6
12
#=end
13

    
14
  Rational(1, 2) - Rational(3, 4)
15
  Rational(1, 2) - 10
16
  Rational(1, 3) - 10.6
17
#=begin
18
  Rational(1, 2) * Rational(3, 4)
19
  Rational(1, 2) * 10
20
  Rational(1, 3) * 10.6
21

    
22
  Rational(1, 2) / Rational(3, 4)
23
  Rational(1, 2) / 10
24
  Rational(1, 3) / 10.6
25

    
26
  Rational(1, 2) ** Rational(3, 4)
27
  Rational(1, 2) ** 10
28
  Rational(1, 2) ** -10
29
  Rational(1, 2) ** 0
30
  Rational(1, 3) ** 10.6
31

    
32
  Rational(1, 2) == Rational(3, 4)
33
  Rational(1, 2) == 10
34
  Rational(1, 3) == 10.6
35

    
36
  Rational(1, 2) <=> Rational(3, 4)
37
  Rational(1, 2) <=> 10
38
  Rational(1, 3) <=> 10.6
39

    
40
  - Rational(1, 2)
41
  - Rational(-1, 3)
42
  - Rational(1, 4)
43

    
44
  Rational(1, 2).abs
45
  Rational(-1, 3).abs
46
  Rational(1, 4).abs
47

    
48
  Rational(1, 2).zero?
49
  Rational(0, 2).zero?
50

    
51
  Rational(1, 2).nonzero?
52
  Rational(0, 2).nonzero?
53

    
54
#=end
55
#=begin
56
  Rational(3, 4).to_s
57
  Rational(5, 6).inspect
58
#=end
59

    
60
END
61

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

    
70
  if $result
71
    unless result == $result
72
      pp result
73
      pp $result
74
      raise "Assertion failed"
75
    end
76
  else
77
    $result = result
78
  end
79
end
80
END
81
else
82
n = 100000
83
n /= 2
84
instance_eval($expr = <<"END", __FILE__, __LINE__)
85
def test_it
86
  #{$tests}
87
end
88
END
89
end
90
$stderr.puts $expr
91

    
92

    
93
Benchmark.bm(40) do | bm |
94

    
95
  1.times do
96
    ObjectSpace.garbage_collect
97
    bm.report("test_it") do 
98
      n.times do
99
        test_it
100
      end
101
    end
102
  end
103

    
104
######################################################################
105

    
106
  if (require('ks_rational') rescue nil)
107
    ObjectSpace.garbage_collect
108
    bm.report("test_it ks_rational") do 
109
      n.times do
110
        test_it
111
      end
112
    end
113
  end
114
    
115
end
116

    
117