File tree 1 file changed +26
-1
lines changed
1 file changed +26
-1
lines changed Original file line number Diff line number Diff line change @@ -374,9 +374,13 @@ impl Rng for ThreadRng {
374
374
/// `random()` can generate various types of random things, and so may require
375
375
/// type hinting to generate the specific type you want.
376
376
///
377
+ /// This function uses the thread local random number generator. This means
378
+ /// that if you're calling `random()` in a loop, caching the generator can
379
+ /// increase performance. An example is shown below.
380
+ ///
377
381
/// # Examples
378
382
///
379
- /// ```rust
383
+ /// ```
380
384
/// use std::rand;
381
385
///
382
386
/// let x = rand::random();
@@ -389,6 +393,27 @@ impl Rng for ThreadRng {
389
393
/// println!("Better lucky than good!");
390
394
/// }
391
395
/// ```
396
+ ///
397
+ /// Caching the thread local random number generator:
398
+ ///
399
+ /// ```
400
+ /// use std::rand;
401
+ /// use std::rand::Rng;
402
+ ///
403
+ /// let mut v = vec![1, 2, 3];
404
+ ///
405
+ /// for x in v.iter_mut() {
406
+ /// *x = rand::random()
407
+ /// }
408
+ ///
409
+ /// // would be faster as
410
+ ///
411
+ /// let mut rng = rand::thread_rng();
412
+ ///
413
+ /// for x in v.iter_mut() {
414
+ /// *x = rng.gen();
415
+ /// }
416
+ /// ```
392
417
#[ inline]
393
418
pub fn random < T : Rand > ( ) -> T {
394
419
thread_rng ( ) . gen ( )
You can’t perform that action at this time.
0 commit comments