簡體   English   中英

人造絲的並行性是否僅限於機器的核心?

[英]Is rayon's parallelism limited to the cores of the machine?

我有以下玩具 Rust 程序:

use rayon::prelude::*;
use std::{env, thread, time};

/// Sleeps 1 second n times
fn seq_sleep(n: usize) {
    for _ in 0..n {
        thread::sleep(time::Duration::from_millis(1000));
    }
}

/// Launches n threads that sleep 1 second
fn thread_sleep(n: usize) {
    let mut handles = Vec::new();
    for _ in 0..n {
        handles.push(thread::spawn(|| {
            thread::sleep(time::Duration::from_millis(1000))
        }));
    }
    for handle in handles {
        handle.join().unwrap();
    }
}

/// Sleeps 1 seconds n times parallely using rayon
fn rayon_sleep(n: usize) {
    let millis = vec![0; n];
    millis
        .par_iter()
        .for_each(|_| thread::sleep(time::Duration::from_millis(1000)));
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let n = args[1].parse::<usize>().unwrap();

    let now = time::Instant::now();
    seq_sleep(n);
    println!("sequential: {:?}", now.elapsed());

    let now = time::Instant::now();
    thread_sleep(n);
    println!("thread: {:?}", now.elapsed());

    let now = time::Instant::now();
    rayon_sleep(n);
    println!("rayon: {:?}", now.elapsed());
}

基本上,我想比較 i) 順序代碼、ii) 基本線程和 iii) 人造絲的並行度。 為此,我的程序接受一個輸入參數n ,並根據方法休眠 1 秒n次。 對於n = 8,我得到以下 output:

sequential: 8.016809707s
thread: 1.006029845s
rayon: 1.004957395s

到目前為止,一切都很好。 但是,對於n = 9,我得到以下 output:

sequential: 9.012422104s
thread: 1.003085005s
rayon: 2.011378713s

順序和基本線程版本對我來說很有意義。 然而,我預計人造絲需要 1 秒。 我的機器有 4 個內核和超線程。 這讓我認為人造絲在內部根據您的機器支持的核心/線程限制並行線程的數量。 它是否正確?

是的:

rayon::ThreadPoolBuilder::build_global()

初始化全局線程池。 此初始化是可選的。 如果不調用這個function,線程池會自動初始化為默認配置。

rayon::ThreadPoolBuilder::num_threads()

如果num_threads為 0,或者你不調用這個 function,那么 Rayon 運行時會自動將線程數設為 select。 目前,這是基於RAYON_NUM_THREADS環境變量(如果已設置)或邏輯 CPU 的數量(否則)。 然而,在未來,默認行為可能會更改為根據需要動態添加或刪除線程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM