Skip to content

Commit bc68102

Browse files
committed
Merge pull request #21059 from steveklabnik/gh16072
Add note about TLS lookups in random() Reviewed-by: huonw
2 parents 7649c10 + 6a7f0a9 commit bc68102

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

src/libstd/rand/mod.rs

+26-1
Original file line numberDiff line numberDiff line change
@@ -374,9 +374,13 @@ impl Rng for ThreadRng {
374374
/// `random()` can generate various types of random things, and so may require
375375
/// type hinting to generate the specific type you want.
376376
///
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+
///
377381
/// # Examples
378382
///
379-
/// ```rust
383+
/// ```
380384
/// use std::rand;
381385
///
382386
/// let x = rand::random();
@@ -389,6 +393,27 @@ impl Rng for ThreadRng {
389393
/// println!("Better lucky than good!");
390394
/// }
391395
/// ```
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+
/// ```
392417
#[inline]
393418
pub fn random<T: Rand>() -> T {
394419
thread_rng().gen()

0 commit comments

Comments
 (0)