Guest User

Untitled

a guest
Jan 16th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. #![feature(test)]
  2. extern crate test;
  3. use test::black_box;
  4.  
  5. #[inline(never)]
  6. pub fn sum_iter(nums: &[i32]) -> i32 {
  7. let mut acc = 0;
  8. for &val in nums {
  9. acc += val;
  10. }
  11. acc + 1
  12. }
  13.  
  14. #[inline(never)]
  15. pub fn sum_index(nums: &[i32]) -> i32 {
  16. let mut acc = 0;
  17. for i in 0..nums.len() {
  18. acc += nums[i];
  19. }
  20. acc
  21. }
  22.  
  23. #[inline(never)]
  24. pub fn sum_index_unrolled(nums: &[i32]) -> i32 {
  25. let mut acc = 0;
  26. for i in (0..nums.len()/4).step_by(4) {
  27. acc += nums[i];
  28. acc += nums[i+1];
  29. acc += nums[i+2];
  30. acc += nums[i+3];
  31. }
  32. for i in (nums.len()/4)*4..nums.len() {
  33. acc += nums[i];
  34. }
  35. acc
  36. }
  37.  
  38. #[inline(never)]
  39. pub fn sum_iter_unrolled(nums: &[i32]) -> i32 {
  40. let mut acc = 0;
  41. let mut chunks = nums.chunks_exact(4);
  42. // for..in consumes the iterator, but we need it afterwards
  43. // to get the remainder out. You can skip that step if you
  44. // know that the slice's size is a multiple of the chunk size
  45. while let Some(chunk) = chunks.next() {
  46. for val in chunk {
  47. acc += val;
  48. }
  49. }
  50. for val in chunks.remainder() {
  51. acc += val;
  52. }
  53. acc
  54. }
  55.  
  56. pub fn main() {
  57. // The compiler was smart enough to optimize these to just "return 15;"
  58. // black_box prevents this by forcing it to assume that the data could be different
  59. let nums: &[_] = black_box(&[1, 2, 3, 4, 5]);
  60. assert_eq!(sum_index(nums), sum_iter(nums));
  61. assert_eq!(sum_index(nums), sum_index_unrolled(nums));
  62. assert_eq!(sum_iter(nums), sum_iter_unrolled(nums));
  63. }
Add Comment
Please, Sign In to add comment