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);
}
-
\$\begingroup\$ I'm not sure this is a suitable question for code review. \$\endgroup\$Stargateur– Stargateur2018年08月31日 05:55:51 +00:00Commented Aug 31, 2018 at 5:55
-
\$\begingroup\$ Hope that is better. \$\endgroup\$Brandon Clark– Brandon Clark2018年08月31日 07:01:18 +00:00Commented Aug 31, 2018 at 7:01
2 Answers 2
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(())
}
You can take advantage of the try operator
?
to make the error handling easier.Similarly, you can add a bit of error handling with the
assert_eq
line. You can use thelen
method because this iterator knows exactly how much elements it has.You can use
skip
to discard the first element of theArgs
iterator.
-
\$\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\$Brandon Clark– Brandon Clark2018年09月07日 05:10:53 +00:00Commented Sep 7, 2018 at 5:10
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.
Explore related questions
See similar questions with these tags.