如何更改功能以与Rayon并行运行?

时间:2019-12-04 22:31:22

标签: rust rayon

我有一个函数,该函数获取数组,开始索引和结束索引。我想返回此数组的最大元素。依次运行正常。但是我不知道如何将其转换为可以使用。所以你能告诉我怎么做。我一直在尝试人造丝的for_each(),但始终会遇到一些错误。转换后的函数看起来如何?

pub fn search_max(array: &[f32], start: i32, end: i32)-> f32 {
    let mut maximum: f32 = A[p as usize];
    let iter: usize = start as usize + 1;
    for iter in iter..end as usize{
        if maximum < array[iter] {
            maximum = array[iter];
        }
    }   
    maximum
}

1 个答案:

答案 0 :(得分:2)

您目前拥有所谓的命令式代码;不能通过功能样式直接将其更改为并行:

pub fn search_max(array: &[f32], start: i32, end: i32) -> f32 {
    let sub_array: &[f32] = &array[start as usize..end as usize];
    *sub_array.iter().max().unwrap()
}

我们使用max方法来获取迭代器产生的最大值。由于f32以来的does not work不能保证很好地订购。 我们将使用max_by来代替闭包:

pub fn search_max(array: &[f32], start: i32, end: i32) -> f32 {
    let sub_array: &[f32] = &array[start as usize..end as usize];

    *    // This results in &f32, so we must dereference it
    sub_array.iter() // Create the iterator over references to the items
    .max_by(
        |x, y| x.partial_cmp(y).unwrap() // https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp
    ).unwrap() // There could possibly be no items! So we get an `Option<&f32>` instead.
}

在大多数情况下,rayon的{​​{3}}是常规迭代器的替代品,因此我们在看到.iter的任何地方都将更改为.par_iter

use rayon::prelude::*;

pub fn search_max(array: &[f32], start: i32, end: i32) -> f32 {
    let sub_array: &[f32] = &array[start as usize..end as usize];
    *sub_array.par_iter().max_by(|x, y| x.partial_cmp(y).unwrap()).unwrap()
}

ParallelIterator


如果您正在寻找最惯用的版本:

pub fn search_max(slice: &'_ [f32], start: usize, end: usize) -> f32 {
    *slice[start..end].par_iter().reduce(
        || &slice[start], // This is an iterator over &'_ f32
        |a, b| if a > b { a } else { b },
    )
}

Playground