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

相关推荐
uzong6 小时前
Mermaid: AI 时代画图的魔法工具
后端·架构
q***69777 小时前
Spring Boot与MyBatis
spring boot·后端·mybatis
IUGEI8 小时前
synchronized的工作机制是怎样的?深入解析synchronized底层原理
java·开发语言·后端·c#
间彧8 小时前
GraalVM Native Image:跨平台能力与编译模式深度解析
后端
间彧8 小时前
GraalVM Native Image 与传统 JVM 内存管理:云原生时代的技术选型指南
后端
r***12388 小时前
SpringBoot最佳实践之 - 使用AOP记录操作日志
java·spring boot·后端
b***74889 小时前
前端GraphQL案例
前端·后端·graphql
LSL666_9 小时前
SpringBoot自动配置类
java·spring boot·后端·自动配置类
q***78379 小时前
Spring Boot 3.X:Unable to connect to Redis错误记录
spring boot·redis·后端
t***265910 小时前
SpringBoot + vue 管理系统
vue.js·spring boot·后端