Parallel processing 程序仍然使用par_iter和par_extend在一个线程上运行

Parallel processing 程序仍然使用par_iter和par_extend在一个线程上运行,parallel-processing,rust,iterator,rayon,Parallel Processing,Rust,Iterator,Rayon,我正在尝试并行化我的代码的一部分,尽管它使用了rayon和并行迭代器par_iter()和par_extend(),但它看起来仍然像是在单个线程上运行 我只需创建一个i32的向量,用很多值填充它,然后将这些值移动到整数的collections::HashSet 我的单线程代码: use std::collections::HashSet; fn main() { let my_vec: Vec<i64> = (0..100_000_000).collect();

我正在尝试并行化我的代码的一部分,尽管它使用了
rayon
和并行迭代器
par_iter()
par_extend()
,但它看起来仍然像是在单个线程上运行

我只需创建一个
i32
的向量,用很多值填充它,然后将这些值移动到整数的
collections::HashSet

我的单线程代码:

use std::collections::HashSet;

fn main() {
    let my_vec: Vec<i64> = (0..100_000_000).collect();

    let mut my_set: HashSet<i64> = HashSet::new();
    let st = std::time::Instant::now();
    my_set.extend(
        my_vec.iter().map(|x| x*(x+3)/77+44741)  // this is supposed to take a while to compute
    );
    let dur = st.elapsed();
    println!("{:?}", dur);

}
“并行”版本的平均运行时间几乎相同(
8.62s
),cpu监视器清楚地显示单个cpu以100%的速度工作,而其他cpu只是等待


你知道我做错了什么,还是不明白

您的模拟不正确,因为您的计算实际上很快,速度非常快,比线程上下文切换快几个数量级。您100%的核心可能是人造丝运行时,而其他核心正在等待它

如果你真的用睡眠来代替你的计算,结果正如你所期望的:

use std::collections::HashSet;
use rayon::prelude::*; // 1.1.0
use std::time::Duration;

fn main() {
    fn slow(i: &i64) -> i64 {
        std::thread::sleep(Duration::from_millis(5));

        *i
    }

    let my_vec: Vec<i64> = (0..100).collect();

    let mut my_set: HashSet<i64> = HashSet::new();

    let st = std::time::Instant::now();
    my_set.extend(
        my_vec.iter().map(slow)  // this is supposed to take a while to compute
    );
    let dur = st.elapsed();
    println!("Regular: {:?}", dur);

    let st = std::time::Instant::now();
    my_set.par_extend(
        my_vec.par_iter().map(slow) // this is supposed to take a while to compute
    );
    let dur = st.elapsed();
    println!("Rayon: {:?}", dur);
}

当你试图优化你的代码时,你必须仔细地对它进行基准测试,因为有时候,当你并行化你的代码时,这会使它变慢。

@FrenchBoiethios谢谢你的评论,它被编辑了,现在看起来更像是“锈音”。我认为它工作得很好:人造丝更慢,这是一个预期结果我认为100%运行的CPU是人造丝运行时。由于计算速度比上下文切换快,因此其他线程的费用较低。好的。。。。这将是一个好兆头,因为我在项目中使用的对象要大得多,表达式
|x | x*(x+3)/77+44741
实际上是一个大的搜索函数,需要几十毫秒。然后我将尝试我的项目,感谢您的洞察力:)
use std::collections::HashSet;
use rayon::prelude::*; // 1.1.0
use std::time::Duration;

fn main() {
    fn slow(i: &i64) -> i64 {
        std::thread::sleep(Duration::from_millis(5));

        *i
    }

    let my_vec: Vec<i64> = (0..100).collect();

    let mut my_set: HashSet<i64> = HashSet::new();

    let st = std::time::Instant::now();
    my_set.extend(
        my_vec.iter().map(slow)  // this is supposed to take a while to compute
    );
    let dur = st.elapsed();
    println!("Regular: {:?}", dur);

    let st = std::time::Instant::now();
    my_set.par_extend(
        my_vec.par_iter().map(slow) // this is supposed to take a while to compute
    );
    let dur = st.elapsed();
    println!("Rayon: {:?}", dur);
}