First NIT release and new clean mercurial repository
[nit.git] / tests / bench_complex_sort.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2006-2008 Jean Privat <jean@pryen.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17
18 class Elt
19 meth val1: Int is abstract
20 meth val2: Int do return val1 end
21 end
22
23 class A
24 special Elt
25 attr _a: Int
26 redef meth val1: Int do return _a end
27
28 init(i: Int) do _a = i end
29 end
30
31 class Elt2
32 special Elt
33 attr _b: Int
34 redef meth val1: Int do return _b/2 end
35 redef meth val2: Int do return _b end
36 end
37
38 class B
39 special Elt2
40
41 init(i: Int) do _b = i end
42 end
43
44 class C
45 special Elt
46 attr _c: Int
47 attr _d: Int
48 redef meth val1: Int do return _c end
49 redef meth val2: Int do return _d end
50
51 init init2(i: Int, j: Int) do
52 _c = i
53 _d = j
54 end
55 end
56
57 class D
58 special A
59 special Elt2
60 redef meth val1: Int do return _a end
61 redef meth val2: Int do return _b end
62
63 init init2(i: Int, j: Int) do
64 init(i)
65 _b = j
66 end
67 end
68
69 class E
70 special Elt2
71 redef meth val1: Int do return 5 end
72
73 init(i: Int) do _b = i end
74 end
75
76 class EltSorter
77 special AbstractSorter[Elt]
78 redef meth compare(a: Elt, b: Elt): Int
79 do
80 if _is_val1 then
81 return a.val1 <=> b.val1
82 else
83 return a.val2 <=> b.val2
84 end
85 end
86
87 meth toggle
88 do
89 _is_val1 = not _is_val1
90 end
91
92 attr _is_val1: Bool
93
94 init do end
95 end
96
97 meth generator: Elt
98 do
99 var r = 5.rand
100 if r == 0 then
101 return new A(10.rand)
102 else if r == 1 then
103 return new B(10.rand)
104 else if r == 2 then
105 return new C.init2(10.rand, 10.rand)
106 else if r == 3 then
107 return new D.init2(10.rand, 10.rand)
108 else
109 return new E(10.rand)
110 end
111 end
112
113 var n = 100
114
115 if not args.is_empty then
116 n = args.first.to_i
117 end
118
119 var array = new Array[Elt].with_capacity(n)
120 for i in [0..n[ do
121 array.push(generator)
122 end
123
124 var sorter = new EltSorter
125 for i in [0..n[ do
126 sorter.sort(array)
127 sorter.toggle
128 end
129