Skip to content

Code in book's example thread not executed #25855

Closed
@naktinis

Description

@naktinis

I'm running the example from the "Rust Inside Other Languages" section in Rust Book.

I noticed that when I embed the code into Python and execute it, the execution time does not depend on the counter size (initially set to 5 million in the book). Although the text suggests it should (we are comparing execution time in different languages after all).

However, if I modify the code to return, say, the count in the spawned thread (and later do .join().unwrap(), the execution time starts depending on the number of iterations.

This seems not to depend on the number of iterations:

pub extern fn process() {
    let handles: Vec<_> = (0..10).map(|_| {
        thread::spawn(|| {
            let mut _x = 0;
            for _ in (0..900_000_001) {
                _x += 1
            }
        })
    }).collect();

    for h in handles {
        h.join().unwrap();
    }
}

This seems to get slower with more iterations (as it should):

pub extern fn process() {
    let handles: Vec<_> = (0..10).map(|_| {
        thread::spawn(|| {
            let mut _x = 0;
            for _ in (0..900_000_001) {
                _x += 1
            }
            _x  // This line makes execution time depend on the number of iterations
        })
    }).collect();

    for h in handles {
        h.join().unwrap();
    }
}

Why is this so? Is this some sort of compiler optimisation that removes the loop execution altogether? Should the code in the book be updated?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions