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

相关推荐
程序员爱钓鱼1 小时前
匿名函数与闭包(Anonymous Functions and Closures)-《Go语言实战指南》原创
后端·golang
言之。2 小时前
Go 语言中接口类型转换为具体类型
开发语言·后端·golang
diving deep3 小时前
XML简要介绍
xml·java·后端
编程乐学(Arfan开发工程师)4 小时前
06、基础入门-SpringBoot-依赖管理特性
android·spring boot·后端
编程乐学(Arfan开发工程师)4 小时前
05、基础入门-SpringBoot-HelloWorld
java·spring boot·后端
橘子海全栈攻城狮5 小时前
【源码+文档+调试讲解】党员之家服务系统小程序1
java·开发语言·spring boot·后端·小程序·旅游
冼紫菜5 小时前
Java开发中使用 RabbitMQ 入门到进阶详解(含注解方式、JSON配置)
java·spring boot·后端·rabbitmq·springcloud
boring_1115 小时前
Apache Pulsar 消息、流、存储的融合
分布式·后端
源码方舟8 小时前
SpringBoot + Shiro + JWT 实现认证与授权完整方案实现
java·spring boot·后端
热河暖男11 小时前
【实战解决方案】Spring Boot+Redisson构建高并发Excel导出服务,彻底解决系统阻塞难题
spring boot·后端·excel