我有一个 struct ,它包含一个2到u32个值的向量(总大小约为8GB).我按照bincode示例将其写入磁盘:

#[macro_use]
extern crate serde_derive;
extern crate bincode;

use std::fs::File;
use bincode::serialize_into;

#[derive(Serialize, Deserialize, PartialEq, Debug)]
pub struct MyStruct {
    counter: Vec<u32>,
    offset: usize,
}

impl MyStruct {
    // omitted for conciseness
}


fn main() {
    let m = MyStruct::new();

    // fill entries in the counter vector

    let mut f = File::create("/tmp/foo.bar").unwrap();
    serialize_into(&mut f, &m).unwrap();
}

为了避免两次分配内存,我使用serialize_into直接写入文件.然而,写作过程真的很慢(大约半小时).有办法加速吗?

推荐答案

这不是serde和/或bincode的问题.与其他一些语言不同,Rust默认情况下不使用缓冲I/O(有关详细信息,请参阅this question).因此,使用缓冲写入程序可以显著提高该代码的性能:

#[macro_use]
extern crate serde_derive;
extern crate bincode;

use std::fs::File;
use bincode::serialize_into;
use std::io::BufWriter;

#[derive(Serialize, Deserialize, PartialEq, Debug)]
pub struct MyStruct {
    counter: Vec<u32>,
    offset: usize,
}

impl MyStruct {
    // omitted for conciseness
}


fn main() {
    let m = MyStruct::new();

    // fill entries in the counter vector

    let mut f = BufWriter::new(File::create("/tmp/foo.bar").unwrap());
    serialize_into(&mut f, &m).unwrap();
}

对我来说,这将写作过程从大约半小时加速到40秒(50倍加速).

Rust相关问答推荐

为什么我们不能通过指针算法将Rust原始指针指向任意地址?'

访问Rust中的隐藏变量

常量泛型和类型枚举箱有重叠的用途吗?

"value is never read警告似乎不正确.我应该忽略它吗?

我如何制作一个变异迭代器来锁定内部数据直到删除?

Trait bound i8:来自u8的不满意

在Rust中声明和定义一个 struct 体有什么区别

将Vec<;U8&>转换为Vec<;{Float}&>

解析程序无法在Cargo 发布中 Select 依赖版本

如何强制匹配的返回类型为()?

如何将 &[T] 或 Vec<T> 转换为 Arc<Mutex<[T]>>?

decltype、dyn、impl traits,重构时如何声明函数的返回类型

如何在 Rust 中将枚举变体转换为 u8?

在 Rust 中实现资源消耗的安全包装器

在线程中运行时,TCPListener(服务器)在 ip 列表中的服务器实例之前没有从客户端接受所有客户端的请求

如何判断服务器是否正确接收数据

为什么传递 option.as_ref 的行为不同于使用匹配块并将内部映射到 ref 自己?

在 Rust 中,将可变引用传递给函数的机制是什么?

无法把握借来的价值不够长寿,请解释

相互调用的递归异步函数:检测到循环