Skip to content

Commit 191b3c8

Browse files
committed
[benchmark] Add RGBHistogramOfObjects
Another dictionary benchmark with objects as key and value types.
1 parent 548ba33 commit 191b3c8

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

benchmark/single-source/RGBHistogram.swift

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,3 +110,63 @@ func createSortedSparseRGBHistogram
110110
}
111111
}
112112
}
113+
114+
class Box<T : Hashable where T : Equatable> : Hashable {
115+
var value: T
116+
117+
init(_ v: T) {
118+
value = v
119+
}
120+
121+
var hashValue : Int {
122+
return value.hashValue
123+
}
124+
}
125+
126+
extension Box : Equatable {
127+
}
128+
129+
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
130+
return lhs.value == rhs.value
131+
}
132+
133+
func isCorrectHistogramOfObjects(histogram: [(key: Box<rrggbb_t>, value: Box<Int>)]) -> Bool {
134+
return histogram.count == 157 &&
135+
histogram[0].0.value == 0x00808080 && histogram[0].1.value == 54 &&
136+
histogram[156].0.value == 0x003B8D96 && histogram[156].1.value == 1
137+
}
138+
139+
func createSortedSparseRGBHistogramOfObjects
140+
<S: Sequence where S.Iterator.Element == rrggbb_t>
141+
(samples: S) -> [(key: Box<rrggbb_t>, value: Box<Int>)] {
142+
var histogram = Dictionary<Box<rrggbb_t>, Box<Int>>()
143+
144+
for sample in samples {
145+
let boxedSample = Box(sample)
146+
let i = histogram.index(forKey: boxedSample)
147+
histogram[boxedSample] = Box(((i != nil) ? histogram[i!].1.value : 0) + 1)
148+
}
149+
150+
return histogram.sorted() {
151+
if $0.1 == $1.1 {
152+
return $0.0.value > $1.0.value
153+
} else {
154+
return $0.1.value > $1.1.value
155+
}
156+
}
157+
}
158+
159+
@inline(never)
160+
public func run_RGBHistogramOfObjects(N: Int) {
161+
var histogram = [(key: Box<rrggbb_t>, value: Box<Int>)]()
162+
for _ in 1...100*N {
163+
histogram = createSortedSparseRGBHistogramOfObjects(samples)
164+
if !isCorrectHistogramOfObjects(histogram) {
165+
break
166+
}
167+
}
168+
CheckResults(isCorrectHistogramOfObjects(histogram),
169+
"Incorrect results in histogram")
170+
}
171+
172+

benchmark/utils/main.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ precommitTests = [
158158
"ProtocolDispatch2": run_ProtocolDispatch2,
159159
"RC4": run_RC4,
160160
"RGBHistogram": run_RGBHistogram,
161+
"RGBHistogramOfObjects": run_RGBHistogramOfObjects,
161162
"RangeAssignment": run_RangeAssignment,
162163
"RecursiveOwnedParameter": run_RecursiveOwnedParameter,
163164
"SetExclusiveOr": run_SetExclusiveOr,

0 commit comments

Comments
 (0)