Created
June 16, 2024 23:21
-
-
Save eginez/831a66406cd18743495fd0317ee31fb4 to your computer and use it in GitHub Desktop.
Mat mul but 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
use rand::Rng; | |
use std::time::SystemTime; | |
fn rand_float() -> f32 { | |
rand::thread_rng().gen::<f32>() | |
} | |
fn calcmatrix(matrix: Vec<Vec<Vec<f32>>>, indices: Vec<Vec<usize>>, big_size: usize) -> Vec<f32> { | |
let mut res = vec![0.0; big_size]; | |
for i in 0..big_size { | |
for j in 0..big_size { | |
let mut acc = 1.0; | |
for z in 0..32 { | |
let i_loc = indices[z][i]; | |
let j_loc = indices[z][j]; | |
acc *= matrix[z][i_loc][j_loc]; | |
} | |
res[i] += acc; | |
} | |
} | |
res | |
} | |
fn main() { | |
let s = 32; | |
let x = 16; | |
let y = 16; | |
let ind_size = 10000; | |
println!("Starting"); | |
// Create 3-dimensional big matrix | |
let mut mat = vec![vec![vec![0.0; y]; x]; s]; | |
// Fill in matrix with random numbers | |
for k in 0..s { | |
for i in 0..x { | |
for j in 0..y { | |
mat[k][i][j] = rand_float(); | |
} | |
} | |
} | |
let mut indices = vec![vec![0; ind_size]; s]; | |
// Fill in indices with numbers from 0 to x | |
for i in 0..s { | |
for j in 0..ind_size { | |
indices[i][j] = rand::thread_rng().gen_range(0..x); | |
} | |
} | |
let start_time = SystemTime::now(); | |
let val = calcmatrix(mat, indices, ind_size); | |
let end_time = SystemTime::now(); | |
let time_taken = end_time | |
.duration_since(start_time) | |
.expect("Clock may have gone backwards"); | |
println!( | |
"Time taken to calc the matrix: {} seconds", | |
time_taken.as_secs_f64() | |
); | |
// println!("val {:?}", val); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment