3
\$\begingroup\$

Are there Rust features I could apply to optimize for simple test of a JPEG or PNG resized from 2000 x 2000 pixels to 150 x 150 pixels?

extern crate image;
use std::env;

fn main() {
    let mut args = env::args();
    args.next();
    let file_location = args.next().unwrap();
    let width = args.next().unwrap().parse().unwrap();
    let height = args.next().unwrap().parse().unwrap();

    let img = image::open(file_location.as_str()).unwrap();

    // img.resize(width, height, image::imageops::Lanczos3);
    img.thumbnail(width, height);
}
\$\endgroup\$
2
  • \$\begingroup\$ I'm not sure this is a suitable question for code review. \$\endgroup\$
    – Stargateur
    Commented Aug 31, 2018 at 5:55
  • \$\begingroup\$ Hope that is better. \$\endgroup\$ Commented Aug 31, 2018 at 7:01

2 Answers 2

5
\$\begingroup\$

I would slightly change this code:

use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    // Args arrangement
    let mut args = std::env::args().skip(1);
    assert_eq!(args.len(), 3, "Arguments must be: file_location width height");

    // Reading args
    let file_location = args.next().unwrap();
    let width = args.next().unwrap().parse()?;
    let height = args.next().unwrap().parse()?;

    // Do the job
    let img = image::open(&file_location)?;
    img.thumbnail(width, height);

    // All was ok
    Ok(())
}
  1. You can take advantage of the try operator ? to make the error handling easier.

  2. Similarly, you can add a bit of error handling with the assert_eq line. You can use the len method because this iterator knows exactly how much elements it has.

  3. You can use skip to discard the first element of the Args iterator.

\$\endgroup\$
1
  • \$\begingroup\$ Thank you very much. Very good pointers for optimizing process flow and enhancing readability. I do not see how this will help me in speeding up the resize process. \$\endgroup\$ Commented Sep 7, 2018 at 5:10
2
\$\begingroup\$

TL;DR;

This cuts approximatly 70% off the resize time.

cargo build --release

You can see the results for each of my test in a repo for comparisons.


From the Cargo Guide:

Compiling in debug mode is the default for development-- compilation time is shorter since the compiler doesn't do optimizations, but the code will run slower. Release mode takes longer to compile, but the code will run faster.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.