Rust创建基准测试bench

打开终端(或命令提示符)。

导航到父目录。

将 Rust 编译器切换到 nightly 版本:

bash 复制代码
rustup default nightly

在该目录下运行 cargo init 命令来创建一个新的 Rust 项目,这将在当前目录下创建 Cargo.tomlsrc 目录:

bash 复制代码
cargo init --lib
复制代码

请注意,我们使用 --lib 选项因为我们将创建一个库项目而不是二进制项目,这通常用于基准测试。

将Rust 代码放入 src 目录中。

Cargo.toml 文件中添加任何必要的依赖项,例如 Criterion 用于基准测试:

bash 复制代码
[dev-dependencies]
criterion = "0.3"

创建基准测试模块。在 benches 目录下创建一个 Rust 源文件,例如 benches/benchmark.rs,并编写您的基准测试代码。

创建一个新的基准测试文件,例如 benches/my_benchmark.rs,并编写您的基准测试代码。以下是一个简单的示例:

rust 复制代码
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use std::fs;
use your_crate_name::{your_split_function, your_read_to_string_function};

fn bench_split_function(c: &mut Criterion) {
    c.bench_function("split", |b| {
        b.iter(|| {
            your_split_function(black_box("path/to/your/testfile.txt"));
        })
    });
}

fn bench_read_to_string_function(c: &mut Criterion) {
    c.bench_function("read_to_string", |b| {
        b.iter(|| {
            your_read_to_string_function(black_box("path/to/your/testfile.txt"));
        })
    });
}

// 引入您要基准测试的函数
use your_crate::process_file;

fn process_file_benchmark(c: &mut Criterion) {
    c.bench_function("process_file_with_split", |b| {
        b.iter(|| {
            // 传递一个文件路径给 process_file 函数
            process_file(&Path::new("path/to/your/file.txt")).unwrap();
        })
    });
}

criterion_group!(benches, process_file_benchmark, bench_split_function, bench_read_to_string_function);
criterion_main!(benches);

构建项目并运行基准测试:

bash 复制代码
cargo bench

这条命令会在包含 Cargo.toml 的目录中查找基准测试,并执行它们。

Criterion 将生成一个 HTML 报告,可以在 target/criterion 目录下找到它,并通过浏览器查看详细的基准测试结果。

相关推荐
крон1 分钟前
【Auto.js例程】华为备忘录导出到其他手机
开发语言·javascript·智能手机
zh_xuan34 分钟前
c++ 单例模式
开发语言·c++·单例模式
coderSong256837 分钟前
Java高级 |【实验八】springboot 使用Websocket
java·spring boot·后端·websocket
老胖闲聊1 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1181 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
Mr_Air_Boy2 小时前
SpringBoot使用dynamic配置多数据源时使用@Transactional事务在非primary的数据源上遇到的问题
java·spring boot·后端
曹勖之2 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
豆沙沙包?2 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
军训猫猫头2 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#
咖啡啡不加糖2 小时前
Redis大key产生、排查与优化实践
java·数据库·redis·后端·缓存