@@ -7,15 +7,21 @@ enum Cache {
77 L3 ,
88}
99
10+ impl Cache {
11+ fn size ( & self ) -> usize {
12+ match self {
13+ Cache :: L1 => 1000 , // 8kb
14+ Cache :: L2 => 10_000 , // 80kb
15+ Cache :: L3 => 1_000_000 , // 8Mb
16+ }
17+ }
18+ }
19+
1020fn binary_search < F > ( b : & mut Bencher , cache : Cache , mapper : F )
1121where
1222 F : Fn ( usize ) -> usize ,
1323{
14- let size = match cache {
15- Cache :: L1 => 1000 , // 8kb
16- Cache :: L2 => 10_000 , // 80kb
17- Cache :: L3 => 1_000_000 , // 8Mb
18- } ;
24+ let size = cache. size ( ) ;
1925 let v = ( 0 ..size) . map ( & mapper) . collect :: < Vec < _ > > ( ) ;
2026 let mut r = 0usize ;
2127 b. iter ( move || {
2430 // Lookup the whole range to get 50% hits and 50% misses.
2531 let i = mapper ( r % size) ;
2632 black_box ( v. binary_search ( & i) . is_ok ( ) ) ;
27- } )
33+ } ) ;
34+ }
35+
36+ fn binary_search_worst_case ( b : & mut Bencher , cache : Cache ) {
37+ let size = cache. size ( ) ;
38+
39+ let mut v = vec ! [ 0 ; size] ;
40+ let i = 1 ;
41+ v[ size - 1 ] = i;
42+ b. iter ( move || {
43+ black_box ( v. binary_search ( & i) . is_ok ( ) ) ;
44+ } ) ;
2845}
2946
3047#[ bench]
@@ -57,6 +74,21 @@ fn binary_search_l3_with_dups(b: &mut Bencher) {
5774 binary_search ( b, Cache :: L3 , |i| i / 16 * 16 ) ;
5875}
5976
77+ #[ bench]
78+ fn binary_search_l1_worst_case ( b : & mut Bencher ) {
79+ binary_search_worst_case ( b, Cache :: L1 ) ;
80+ }
81+
82+ #[ bench]
83+ fn binary_search_l2_worst_case ( b : & mut Bencher ) {
84+ binary_search_worst_case ( b, Cache :: L2 ) ;
85+ }
86+
87+ #[ bench]
88+ fn binary_search_l3_worst_case ( b : & mut Bencher ) {
89+ binary_search_worst_case ( b, Cache :: L3 ) ;
90+ }
91+
6092macro_rules! rotate {
6193 ( $fn: ident, $n: expr, $mapper: expr) => {
6294 #[ bench]
0 commit comments