Skip to content

Instantly share code, notes, and snippets.

@ming900518
Created December 27, 2023 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ming900518/8ad34be29b87ecfa336bef111825c761 to your computer and use it in GitHub Desktop.
Save ming900518/8ad34be29b87ecfa336bef111825c761 to your computer and use it in GitHub Desktop.
Rust SIMD mul operation test
#![feature(portable_simd)]
use rand::random;
use std::{array::from_fn, simd::Simd, time::Instant};
#[inline]
fn main() {
let test: [f32; 64] = from_fn(|_| random());
let random_magic: f32 = random();
let test_2: [f32; 64] = [random_magic; 64];
println!("Data for test: {test:?}");
let simd_start = Instant::now();
let simd_result = simd(test, test_2);
println!("SIMD: {} ns", simd_start.elapsed().as_nanos());
let normal_start = Instant::now();
let normal_result = normal(test, random_magic);
println!("Normal: {} ns", normal_start.elapsed().as_nanos());
assert_eq!(simd_result, normal_result);
}
#[no_mangle]
#[inline]
fn simd(input: [f32; 64], mul: [f32; 64]) -> [f32; 64] {
let input = Simd::from_array(input);
let mul = Simd::from_array(mul);
(input * mul).to_array()
}
#[no_mangle]
#[inline]
fn normal(input: [f32; 64], mul: f32) -> [f32; 64] {
input
.into_iter()
.map(|v| v * mul)
.collect::<Vec<_>>()
.try_into()
.unwrap()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment