ruuda / claxon

A FLAC decoder in Rust
Apache License 2.0
285 stars 28 forks source link

FLAC file reading performance #9

Closed lpil closed 6 years ago

lpil commented 6 years ago

Hello!

First thank you for this library. I've found it very approachable as a Rust beginner :)

I've written some code that reads a Flac file into memory as a Vec<f32> based off one of the given examples.

const CHANNELS: usize = 2;
type Sample = f32;
type Frame = [Sample; CHANNELS];
type Media = Vec<Frame>;

pub fn read_flac(path: String) -> Media {
    let mut reader = claxon::FlacReader::open(path).expect("Unable to open FLAC file");
    let mut samples = reader.samples();
    let capacity = (audio_engine::SAMPLE_HZ * 60.0 * 10.0) as usize;
    let mut frames = Vec::with_capacity(capacity);

    while let (Some(Ok(l)), Some(Ok(r))) = (samples.next(), samples.next()) {
        frames.push([l as Sample, r as Sample]);
    }

    frames.shrink_to_fit();
    frames
}

fn main() {
    println!("About to read file");
    let _media = media::read_flac("../media/music.flac".to_string());
    println!("Done");
}

When I run this it takes longer than I would expect.

louis ~/projects/decksterity/rust [master *] $ time cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
     Running `target/debug/decksterity`
about to read file
done

real    0m21.641s
user    0m21.604s
sys     0m0.028s

Here the given input file was 26MiB and it took 22 seconds to read it.

This is slower than I would expect, other programs (not written by me) on the same machine seem to be able to read the entire file in less than a second.

Have I made a mistake in my implementation here?

Thanks, Louis

ruuda commented 6 years ago

Have you tried running it in release mode with cargo run --release? By default, cargo run will compile the program in debug mode. In debug mode, Rust performs overflow checks on integer arithmetic. Decoding Flac involves a lot of integer arithmetic, therefore Claxon is quite a bit slower in debug mode than in release.

lpil commented 6 years ago

Gosh, now it runs in half a second. I feel very foolish! Thank you for your help :)