Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #![feature(test)]
- extern crate test;
- use test::black_box;
- #[inline(never)]
- pub fn sum_iter(nums: &[i32]) -> i32 {
- let mut acc = 0;
- for &val in nums {
- acc += val;
- }
- acc + 1
- }
- #[inline(never)]
- pub fn sum_index(nums: &[i32]) -> i32 {
- let mut acc = 0;
- for i in 0..nums.len() {
- acc += nums[i];
- }
- acc
- }
- #[inline(never)]
- pub fn sum_index_unrolled(nums: &[i32]) -> i32 {
- let mut acc = 0;
- for i in (0..nums.len()/4).step_by(4) {
- acc += nums[i];
- acc += nums[i+1];
- acc += nums[i+2];
- acc += nums[i+3];
- }
- for i in (nums.len()/4)*4..nums.len() {
- acc += nums[i];
- }
- acc
- }
- #[inline(never)]
- pub fn sum_iter_unrolled(nums: &[i32]) -> i32 {
- let mut acc = 0;
- let mut chunks = nums.chunks_exact(4);
- // for..in consumes the iterator, but we need it afterwards
- // to get the remainder out. You can skip that step if you
- // know that the slice's size is a multiple of the chunk size
- while let Some(chunk) = chunks.next() {
- for val in chunk {
- acc += val;
- }
- }
- for val in chunks.remainder() {
- acc += val;
- }
- acc
- }
- pub fn main() {
- // The compiler was smart enough to optimize these to just "return 15;"
- // black_box prevents this by forcing it to assume that the data could be different
- let nums: &[_] = black_box(&[1, 2, 3, 4, 5]);
- assert_eq!(sum_index(nums), sum_iter(nums));
- assert_eq!(sum_index(nums), sum_index_unrolled(nums));
- assert_eq!(sum_iter(nums), sum_iter_unrolled(nums));
- }
Add Comment
Please, Sign In to add comment