File tree Expand file tree Collapse file tree 2 files changed +21
-9
lines changed
Expand file tree Collapse file tree 2 files changed +21
-9
lines changed Original file line number Diff line number Diff line change @@ -250,11 +250,7 @@ impl Addr for String {
250250
251251impl < A : Addr > Addr for Vec < A > {
252252 fn addr ( & self ) -> & str {
253- if self . len ( ) == 0 {
254- ""
255- } else {
256- & self [ 0 ] . addr ( )
257- }
253+ if self . len ( ) == 0 { "" } else { & self [ 0 ] . addr ( ) }
258254 }
259255 fn visit ( & self , f : & mut dyn FnMut ( & str ) ) {
260256 for a in self {
@@ -300,6 +296,10 @@ where
300296 ( a. addr ( ) . to_string ( ) , max)
301297 } )
302298 . collect ( ) ;
299+
300+ // 为每个元素预先生成随机值,确保比较函数的一致性
301+ let mut random_values: HashMap < String , u16 > = HashMap :: new ( ) ;
302+
303303 self . sort_by ( |a, b| {
304304 let da = distances[ a. addr ( ) ] ;
305305 let db = distances[ b. addr ( ) ] ;
@@ -310,8 +310,20 @@ where
310310 let cb = b. count ( & top) ;
311311 cb. cmp ( & ca)
312312 } )
313- // 距离相同时,随机排序。避免可能的热点
314- . then_with ( || rand:: random :: < u16 > ( ) . cmp ( & ( u16:: MAX / 2 ) ) )
313+ // 距离相同时,使用预先生成的随机值排序。避免可能的热点
314+ . then_with ( || {
315+ // 获取或生成a的随机值
316+ let ra = * random_values
317+ . entry ( a. addr ( ) . to_string ( ) )
318+ . or_insert ( rand:: random :: < u16 > ( ) ) ;
319+
320+ // 获取或生成b的随机值
321+ let rb = * random_values
322+ . entry ( b. addr ( ) . to_string ( ) )
323+ . or_insert ( rand:: random :: < u16 > ( ) ) ;
324+
325+ ra. cmp ( & rb)
326+ } )
315327 } ) ;
316328
317329 let mut len_local = 0 ;
Original file line number Diff line number Diff line change 1- use criterion:: { black_box , Criterion } ;
1+ use criterion:: { Criterion , black_box } ;
22pub ( super ) fn bench_num_to_str ( c : & mut Criterion ) {
33 let mut group = c. benchmark_group ( "num_to_str" ) ;
44 let end = 999 ;
@@ -41,7 +41,7 @@ pub(super) fn bench_num_to_str(c: &mut Criterion) {
4141pub ( super ) fn bench_mod ( c : & mut Criterion ) {
4242 use rand:: Rng ;
4343 let mut r = rand:: thread_rng ( ) ;
44- let ( range, interval) = if r. gen :: < bool > ( ) {
44+ let ( range, interval) = if r. r# gen:: < bool > ( ) {
4545 ( 1024usize , 32usize )
4646 } else {
4747 ( 512 , 32 )
You can’t perform that action at this time.
0 commit comments