与C相比,Rust文件I / O非常慢。出了什么问题?

时间:2017-03-26 12:24:40

标签: performance file io rust

为了比较C和Rust之间的文件I / O性能,我将“test”写入文件100,000,000次,并从文件中读取4个字节100,000,000次。

与C相比,Rust代码花费了超过450倍的sys时间用于写入,140次用于读取。

我怀疑有更好的方法来实现快速I / O;如何提高Rust中文件I / O的性能?

$ rustc --version
rustc 1.16.0
$ rustc rswrite.rs -C opt-level=3  # Rust for writing
$ time ./rswrite
real    1m8.411s
user    0m3.817s
sys     1m4.533s
$ rustc rsread.rs -C opt-level=3  # Rust for reading
$ time ./rsread
real    0m18.077s
user    0m2.130s
sys     0m15.910s
$ gcc -O3 cwrite.c -ocwrite  # C for writing
$ time ./cwrite
real    0m1.564s
user    0m1.397s
sys     0m0.143s
$ gcc -O3 cread.c -ocread  # C for reading
$ time ./cread
real    0m1.353s
user    0m1.240s
sys     0m0.113s

写作的Rust代码:

use std::fs;
use std::io::Write;
fn main() {
    let b = b"test";
    let mut f = fs::File::create("rs.dump").unwrap();
    for _ in 0 .. 100_000_000 {
        f.write(b).unwrap();
    }
}

阅读的Rust代码:

use std::{fs, mem};
use std::io::Read;
fn main() {
    let mut f = fs::File::open("rs.dump").unwrap();
    let mut b: [u8; 4] = unsafe { mem::uninitialized() };
    for _ in 0 .. 100_000_000 {
        f.read_exact(&mut b).unwrap();
    }
}

写作的C代码:

#include <stdio.h>
#define N 100000000
int main()
{
    const char *teststr = "test";
    FILE *fp = fopen("c.dump", "wb");
    unsigned long long i;
    for (i=0; i<N; i++) fwrite(teststr, 4, 1, fp);
    fclose(fp);
    return 0;
}

阅读的C代码:

#include <stdio.h>
#define N 100000000

int main() {
    FILE *fp = fopen("c.dump", "rb");
    long long i;
    char buf[4];
    for (i=0; i<N; i++) fread(buf, 4, 1, fp);
    fclose(fp);
    return 0;
}

1 个答案:

答案 0 :(得分:14)

我的Rust程序没有使用缓冲IO。感谢BurntSushi5和Andrew Henle的评论,问题解决了。

$ strace ./rswrite
write(3, "test", 4)                     = 4
write(3, "test", 4)                     = 4
...
$ strace ./rswrite
read(3, "test", 4)                      = 4
read(3, "test", 4)                      = 4
...

我修改了代码:

use std::fs;
use std::io::{BufWriter, Write};
fn main() {
    let b = b"test";
    /**** Use std::io::BufWriter ****/
    let mut f = BufWriter::new(fs::File::create("rs.dump").unwrap());
    for _ in 0 .. 100_000_000 {
        f.write(b).unwrap();
    }
}

use std::{fs, mem};
use std::io::{BufReader, Read};
fn main() {
    /**** Use std::io::BufReader ****/
    let mut f = BufReader::new(fs::File::open("rs.dump").unwrap());
    let mut b: [u8; 4] = unsafe { mem::uninitialized() };
    for _ in 0 .. 100_000_000 {
        f.read_exact(&mut b).unwrap();
    }
}

现在,I / O被缓冲了。

write(3, "testtesttesttesttesttesttesttest"..., 8192) = 8192
write(3, "testtesttesttesttesttesttesttest"..., 8192) = 8192
...

表现与C一样快。

$ time ./rswrite
real    0m1.341s
user    0m0.213s
sys     0m0.200s
$ time ./rsread_buf
real    0m0.596s
user    0m0.540s
sys     0m0.050s