multithreading - Rayon 会避免为少量工作生成线程吗?

标签 multithreading rust rayon

我正在考虑使用 Rayon 的并行迭代器功能,但我担心迭代小型集合的性能。

并行开销有时会导致小型集合变慢。如果我为多线程做必要的准备,迭代 2 个元素会比使用单线程版本慢。如果我有 4000 万个元素,并行性将使我的性能得到线性提升。

我读到了 ParallelIterator::weight (0.6.0) ,但我不明白我是否应该针对小型集合优化此类边角情况,或者 Rayon 是否很聪明并且可以处理幕后的所有事情。

if collection_is_small() {
    // Run single threaded version... 
} else {
    // Use parallel iterator.
}

ParallelIterator::weight被处理元素的个数为1。请参阅相关文档以获得良好的定义,但单个元素的处理成本很低。

Google 将我转到旧文档页面。 Weight 已弃用 removed从 0.8.0 版本开始。

最佳答案

Weight API 已弃用,取而代之的是 split length control . 默认情况下,Rayon 将在每个项目 处拆分,有效地使所有计算并行,此行为可以通过配置 with_min_len .

Sets the minimum length of iterators desired to process in each thread. Rayon will not split any smaller than this length, but of course an iterator could already be smaller to begin with.

Producers like zip and interleave will use greater of the two minimums. Chained iterators and iterators inside flat_map may each use their own minimum length.

extern crate rayon; // 1.0.3
use rayon::prelude::*;
use std::thread;

fn main() {
    println!("Main thread: {:?}", thread::current().id());
    let ids: Vec<_> = (0..4)
        .into_par_iter()
        .with_min_len(4)
        .map(|_| thread::current().id())
        .collect();
    println!("Iterations: {:?}", ids);
}

输出:

Main thread: ThreadId(0)
Iterations: [ThreadId(0), ThreadId(0), ThreadId(0), ThreadId(0)]

Playground (感谢@shepmaster 提供代码)

关于multithreading - Rayon 会避免为少量工作生成线程吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54605692/

相关文章:

memory - 线程 'main'对 'attempt to multiply with overflow'感到 panic

multithreading - 使用rusoto使用rust AWS分段上传,对 'there is no reactor running …`感到 panic 的多线程(人造丝)

Rust 线​​程池每个线程中都有初始化代码?

rust - 如何从Rayon的 `par_iter()`引起 panic ?

java - 如何从服务器发送 html 文件以在客户端浏览器中打开?

java - Java线程中的定时器

rust - 如何避免在 stdin 和 stdout 上缓冲?

c# - 带套接字的C#线程

.net 多线程

rust - "consider removing this semicolon"错误