Project

General

Profile

Feature #2561 ยป rational_performance.rb

kstephens (Kurt Stephens), 01/07/2010 03:43 AM

 
1
require 'benchmark'
2

    
3
require 'rational'
4

    
5
$result = nil
6

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

    
14
  Rational(1, 2) - Rational(3, 4)
15
  Rational(1, 2) - 10
16
  Rational(1, 3) - 10.6
17
  10             - Rational(1, 2)
18
  10.6           - Rational(1, 3)
19

    
20
  Rational(1, 2) * Rational(3, 4)
21
  Rational(1, 2) * 10
22
  Rational(1, 3) * 10.6
23
  10             * Rational(1, 2)
24
  10.6           * Rational(1, 3)
25

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

    
32
  Rational(1, 2) ** Rational(3, 4)
33
  Rational(1, 2) ** 10
34
  Rational(1, 2) ** -10
35
  Rational(1, 2) ** 0
36
  Rational(1, 3) ** 10.6
37
  10             ** Rational(1, 2)
38
  10.6           ** Rational(1, 2)
39
 
40
  Rational(1, 2) == Rational(3, 4)
41
  Rational(1, 2) == 10
42
  Rational(1, 3) == 10.6
43
  10             == Rational(1, 2)
44
  10.6           == Rational(1, 3)
45

    
46
  Rational(1, 2) <=> Rational(3, 4)
47
  Rational(1, 2) <=> 10
48
  Rational(1, 3) <=> 10.6
49
  10             <=> Rational(1, 2)
50
  10.6           <=> Rational(1, 3)
51

    
52
  - Rational(1, 2)
53
  - Rational(-1, 3)
54
  - Rational(1, 4)
55

    
56
  Rational(1, 2).abs
57
  Rational(-1, 3).abs
58
  Rational(1, 4).abs
59

    
60
  Rational(1, 2).zero?
61
  Rational(0, 2).zero?
62

    
63
  Rational(1, 2).nonzero?
64
  Rational(0, 2).nonzero?
65

    
66
  Rational(3, 4).to_s
67
  Rational(5, 6).inspect
68
END
69

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

    
78
  if $result
79
    unless result == $result
80
      pp result
81
      pp $result
82
      raise "Assertion failed"
83
    end
84
  else
85
    $result = result
86
  end
87
end
88
END
89
else
90
n = 100000
91
n /= 2
92
instance_eval($expr = <<"END", __FILE__, __LINE__)
93
def test_it
94
  #{$tests}
95
end
96
END
97
end
98
$stderr.puts $expr
99

    
100

    
101
Benchmark.bm(40) do | bm |
102

    
103
  1.times do
104
    ObjectSpace.garbage_collect
105
    bm.report("test_it") do 
106
      n.times do
107
        test_it
108
      end
109
    end
110
  end
111

    
112
######################################################################
113

    
114
  if (require('ks_rational') rescue nil)
115
    ObjectSpace.garbage_collect
116
    bm.report("test_it ks_rational") do 
117
      n.times do
118
        test_it
119
      end
120
    end
121
  end
122
    
123
end
124

    
125