Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::time::Instant;
- fn main() {
- let bencher = Bencher {
- width: 500,
- height: 5000,
- runs: 20,
- };
- let a = bencher.bench(WithIndices);
- let b = bencher.bench(WithIterators);
- assert_eq!(a, b);
- }
- struct Bencher {
- width: usize,
- height: usize,
- runs: usize,
- }
- impl Bencher {
- fn bench<F: Method>(&self, f: F) -> Vec<u8> {
- let (width, height) = (self.width, self.height);
- let mut collection =vec![0; width*height*4];
- let t0 = Instant::now();
- for _ in 0..self.runs {
- for b in &mut collection { *b = 255; }
- f.calc(&mut collection, width, height);
- }
- let elapsed = t0.elapsed();
- println!("{} runs of {} took {} ms", self.runs, F::TITLE, elapsed.as_millis());
- collection
- }
- }
- trait Method {
- const TITLE: &'static str;
- fn calc(&self, collection: &mut [u8], width: usize, height: usize);
- }
- struct WithIndices;
- impl Method for WithIndices {
- const TITLE: &'static str = "with_indices";
- fn calc(&self, collection: &mut [u8], width: usize, height: usize) {
- for j in 0..height {
- for i in 0..width {
- if i >= width/4 && i < width*3/4 {
- let idx = (i + j * width) * 4;
- collection[idx] = 0;
- collection[idx + 1] = 0;
- collection[idx + 2] = 0;
- }
- }
- }
- }
- }
- struct WithIterators;
- impl Method for WithIterators {
- const TITLE: &'static str = "with_iterators";
- fn calc(&self, collection: &mut [u8], width: usize, _height: usize) {
- /*
- let pixels = collection
- .chunks_mut(4 * width)
- .flat_map(|line| line.chunks_mut(4).skip(width / 4).take(width / 2));
- */
- //for pixel in pixels {
- for pixel in collection.chunks_mut(4 * width).flat_map(|line| line[width .. width * 3].chunks_mut(4)) {
- pixel[.. 3].copy_from_slice(&[0, 0, 0]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement