Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. use std::time::Instant;
  2.  
  3. fn main() {
  4. let bencher = Bencher {
  5. width: 500,
  6. height: 5000,
  7. runs: 20,
  8. };
  9. let a = bencher.bench(WithIndices);
  10. let b = bencher.bench(WithIterators);
  11. assert_eq!(a, b);
  12. }
  13.  
  14. struct Bencher {
  15. width: usize,
  16. height: usize,
  17. runs: usize,
  18. }
  19.  
  20. impl Bencher {
  21. fn bench<F: Method>(&self, f: F) -> Vec<u8> {
  22. let (width, height) = (self.width, self.height);
  23. let mut collection =vec![0; width*height*4];
  24. let t0 = Instant::now();
  25. for _ in 0..self.runs {
  26. for b in &mut collection { *b = 255; }
  27. f.calc(&mut collection, width, height);
  28. }
  29. let elapsed = t0.elapsed();
  30. println!("{} runs of {} took {} ms", self.runs, F::TITLE, elapsed.as_millis());
  31. collection
  32. }
  33. }
  34.  
  35. trait Method {
  36. const TITLE: &'static str;
  37.  
  38. fn calc(&self, collection: &mut [u8], width: usize, height: usize);
  39. }
  40.  
  41. struct WithIndices;
  42.  
  43. impl Method for WithIndices {
  44. const TITLE: &'static str = "with_indices";
  45.  
  46. fn calc(&self, collection: &mut [u8], width: usize, height: usize) {
  47. for j in 0..height {
  48. for i in 0..width {
  49. if i >= width/4 && i < width*3/4 {
  50. let idx = (i + j * width) * 4;
  51. collection[idx] = 0;
  52. collection[idx + 1] = 0;
  53. collection[idx + 2] = 0;
  54. }
  55. }
  56. }
  57. }
  58. }
  59.  
  60. struct WithIterators;
  61.  
  62. impl Method for WithIterators {
  63. const TITLE: &'static str = "with_iterators";
  64.  
  65. fn calc(&self, collection: &mut [u8], width: usize, _height: usize) {
  66. /*
  67. let pixels = collection
  68. .chunks_mut(4 * width)
  69. .flat_map(|line| line.chunks_mut(4).skip(width / 4).take(width / 2));
  70. */
  71. //for pixel in pixels {
  72. for pixel in collection.chunks_mut(4 * width).flat_map(|line| line[width .. width * 3].chunks_mut(4)) {
  73. pixel[.. 3].copy_from_slice(&[0, 0, 0]);
  74. }
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement