使用Rust Rayon库提升程序运行速度

本文是对 N倍性能提升!无痛Rust并行编程:Rayon库初体验[1]的学习与记录

有这样一段程序,计算1到1亿的连续数字之和

复制代码
use std::i64;

fn main() {

    let arr:Vec<i64> = (1..1_0000_0000).collect();

    let result = sum_of_add(&arr);

    println!("{}",result);
}


fn sum_of_add(input: &[i64]) -> i64 {

    input.iter()
    .map(|&i| i + i)
    .sum()

}

添加部分代码,统计程序执行时间

复制代码
use std::{i64, time::SystemTime};

fn main() {
    let arr: Vec<i64> = (1..1_0000_0000).collect();

    let time_a = SystemTime::now();

    let result = sum_of_add(&arr);

    println!("{}", result);

    let time_b = SystemTime::now().duration_since(time_a);
    println!("{:?}", time_b);
}

fn sum_of_add(input: &[i64]) -> i64 {
    input.iter().map(|&i| i + i).sum()
}

执行 cargo run --release, 输出:

复制代码
9999999900000000
Ok(67.672ms)

考虑使用Rayon。这是一个并行计算库,利用work-steal思想,让负载不高的线程,去分担其他线程的工作

在cargo.toml文件的dependence处新增 rayon = "1.8"

在代码中use rayon::prelude::*;

同时将 input.iter().map(|&i| i + i).sum() 改为 input.par_iter().map(|&i| i + i).sum()即可。 par即parallel

复制代码
use std::{i64, time::SystemTime};
use rayon::prelude::*;

fn main() {
    let arr: Vec<i64> = (1..1_0000_0000).collect();

    let time_a = SystemTime::now();

    let result = sum_of_add(&arr);

    println!("{}", result);

    let time_b = SystemTime::now().duration_since(time_a);
    println!("{:?}", time_b);
}

fn sum_of_add(input: &[i64]) -> i64 {
    input.par_iter().map(|&i| i + i).sum()
}

再次 cargo run --release

结果为:

复制代码
9999999900000000
Ok(29.368ms)

提升了一倍有余。

如果不加 --release,相差更多。

rayon相关代码解析[2]

更多阅读

【每周一库】- Rayon 数据并行计算库[3]

Rust Cookbook 中文版-数据并行[4] 和 Rust 烹饪书-并行任务[5] 只有翻译的区别

参考资料

1

N倍性能提升!无痛Rust并行编程:Rayon库初体验: https://www.bilibili.com/video/BV1Rz4y1P791

2

rayon相关代码解析: https://github.com/cuishuang/explain-rust-source-code-by-chatgpt/tree/main/rayon

3

【每周一库】- Rayon 数据并行计算库: https://rustcc.cn/article?id=181e0a73-6742-42a9-b7a1-1c00bef436c2

4

Rust Cookbook 中文版-数据并行: https://rustwiki.org/zh-CN/rust-cookbook/concurrency/parallel.html

5

Rust 烹饪书-并行任务: https://llever.com/rust-cookbook-zh/concurrency/parallel.zh.html

本文由mdnice多平台发布

相关推荐
程序猿DD17 分钟前
JUnit 5 中的 @ClassTemplate 实战指南
java·后端
Victor35639 分钟前
Netty(14)如何处理Netty中的异常和错误?
后端
Victor3561 小时前
Netty(13)Netty中的事件和回调机制
后端
码事漫谈2 小时前
VS Code 1.107 更新:多智能体协同与开发体验升级
后端
码事漫谈2 小时前
从概念开始开始C++管道编程
后端
@淡 定2 小时前
Spring中@Autowired注解的实现原理
java·后端·spring
serendipity_hky3 小时前
【go语言 | 第2篇】Go变量声明 + 常用数据类型的使用
开发语言·后端·golang
疯狂的程序猴3 小时前
App Store上架完整流程与注意事项详解
后端
开心就好20253 小时前
把 H5 应用上架 App Store,并不是套个壳这么简单
后端