Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit df3a639

Browse files
miguelrazworkingjubilee
authored andcommitted
add dot_product example
1 parent 1547dd6 commit df3a639

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Code taken from the `packed_simd` crate
2+
// Run this code with `cargo test --example dot_product`
3+
#![feature(array_chunks)]
4+
use core_simd::*;
5+
6+
pub fn dot_prod(a: &[f32], b: &[f32]) -> f32 {
7+
assert_eq!(a.len(), b.len());
8+
9+
// TODO handle remainder when a.len() % 4 != 0
10+
a.array_chunks::<4>()
11+
.map(|&a| f32x4::from_array(a))
12+
.zip(b.array_chunks::<4>().map(|&b| f32x4::from_array(b)))
13+
.map(|(a, b)| (a * b).horizontal_sum())
14+
.sum()
15+
}
16+
17+
fn main() {
18+
// Empty main to make cargo happy
19+
}
20+
21+
#[cfg(test)]
22+
mod tests {
23+
#[test]
24+
fn test() {
25+
use super::*;
26+
let a: Vec<f32> = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
27+
let b: Vec<f32> = vec![-8.0, -7.0, -6.0, -5.0, 4.0, 3.0, 2.0, 1.0];
28+
29+
assert_eq!(0.0, dot_prod(&a, &b));
30+
}
31+
}

0 commit comments

Comments
 (0)