使用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多平台发布

相关推荐
Blockchain1 分钟前
从头开始使用 Go 构建 Orchestrator(第 六部分:指标)
后端·kubernetes
iOS开发上架哦4 分钟前
mobileconfig文件ios怎么安装
后端
Blockchain5 分钟前
从头开始使用 Go 构建 Orchestrator(第五部分:Worker 的 API)
后端·kubernetes
〆、风神20 分钟前
Spring Boot 自定义定时任务组件深度解析:Quartz 集成与设计模式实战
spring boot·后端·设计模式
拖拉机33 分钟前
Python(八)类(下)
后端·python
D龙源38 分钟前
VSCode进程间通信构建过程详解
后端·架构
开心就好202541 分钟前
【Flutter】Flutter 打开第三方应用 ( url_launcher 插件搜索与安装 | url_launcher 插件官方示例 | 打开浏览器 |
后端
海拥1 小时前
突破反爬限制的智能数据采集实战 —— 面向中小企业的高效信息监控方案
后端
uhakadotcom1 小时前
Google Cloud IoT 平台入门:基础架构与示例详解
后端·面试·github
雷渊1 小时前
ES不支持decimal,如何避免丢失精度?
java·后端·面试