File tree Expand file tree Collapse file tree 2 files changed +32
-1
lines changed Expand file tree Collapse file tree 2 files changed +32
-1
lines changed Original file line number Diff line number Diff line change @@ -73,3 +73,26 @@ fn u32_fastrand(b: &mut Bencher) {
73
73
sum
74
74
} )
75
75
}
76
+
77
+ #[ bench]
78
+ fn fill ( b : & mut Bencher ) {
79
+ let rng = fastrand:: Rng :: new ( ) ;
80
+ b. iter ( || {
81
+ // Pick a size that isn't divisble by 8.
82
+ let mut bytes = [ 0u8 ; 367 ] ;
83
+ rng. fill ( & mut bytes) ;
84
+ bytes
85
+ } )
86
+ }
87
+
88
+ #[ bench]
89
+ fn fill_naive ( b : & mut Bencher ) {
90
+ let rng = fastrand:: Rng :: new ( ) ;
91
+ b. iter ( || {
92
+ let mut bytes = [ 0u8 ; 367 ] ;
93
+ for item in & mut bytes {
94
+ * item = rng. u8 ( ..) ;
95
+ }
96
+ bytes
97
+ } )
98
+ }
Original file line number Diff line number Diff line change @@ -444,7 +444,15 @@ impl Rng {
444
444
/// Fill a byte slice with random data.
445
445
#[ inline]
446
446
pub fn fill ( & self , slice : & mut [ u8 ] ) {
447
- for item in slice {
447
+ // Filling the buffer in chunks of 8 is much faster.
448
+ let mut chunks = slice. chunks_exact_mut ( 8 ) ;
449
+ for items in chunks. by_ref ( ) {
450
+ let r = self . u64 ( ..) ;
451
+ items. copy_from_slice ( & r. to_le_bytes ( ) ) ;
452
+ }
453
+
454
+ let remainder = chunks. into_remainder ( ) ;
455
+ for item in remainder {
448
456
* item = self . u8 ( ..) ;
449
457
}
450
458
}
You can’t perform that action at this time.
0 commit comments