Created
October 30, 2020 10:37
-
-
Save JRF63/9a6268b91720958e90dbe7abffe20298 to your computer and use it in GitHub Desktop.
Matrix multiply microbenchmark for Polly in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![allow(dead_code)] | |
#![feature(test)] | |
extern crate test; | |
use test::Bencher; | |
const N: usize = 256; | |
#[repr(C, align(16))] | |
struct Matrix([f64; N * N]); | |
impl Matrix { | |
fn zeroes() -> Box<Self> { | |
unsafe { | |
let layout = std::alloc::Layout::new::<Matrix>(); | |
let ptr = std::alloc::alloc_zeroed(layout) as *mut Matrix; | |
Box::from_raw(ptr) | |
} | |
} | |
fn ones() -> Box<Self> { | |
let mut matrix = Matrix::zeroes(); | |
for i in 0..N { | |
matrix.0[i] = 1.0; | |
} | |
matrix | |
} | |
fn gemm(a: &Matrix, b: &Matrix, c: &mut Matrix) { | |
for i in 0..N { | |
for j in 0..N { | |
let mut acc = 0.0; | |
for k in 0..N { | |
unsafe { | |
acc += (*a.0.get_unchecked(i * N + k)) * (*b.0.get_unchecked(k * N + j)); | |
} | |
} | |
unsafe { | |
*(c.0.get_unchecked_mut(i * N + j)) = acc; | |
} | |
} | |
} | |
} | |
} | |
#[bench] | |
fn gemm_bench(bencher: &mut Bencher) { | |
let a = Matrix::ones(); | |
let b = Matrix::ones(); | |
let mut c = Matrix::zeroes(); | |
bencher.iter(|| { | |
Matrix::gemm(&a, &b, &mut c); | |
test::black_box(&mut c); | |
}); | |
} | |
#[bench] | |
fn summarize(bencher: &mut Bencher) { | |
if let Some(summary) = bencher.bench(gemm_bench) { | |
println!("{:?}", summary); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment