Skip to content

Instantly share code, notes, and snippets.

@IsaacGemal
Last active October 14, 2024 15:48
Show Gist options
  • Save IsaacGemal/404565c8136f46d0c623e4b373ec0f8c to your computer and use it in GitHub Desktop.
Save IsaacGemal/404565c8136f46d0c623e4b373ec0f8c to your computer and use it in GitHub Desktop.
// Quick rust matrix math benchmark, written by GPT
use nalgebra::{DMatrix, DVector}; // Make sure to add nalgebra to your Cargo.toml file under [dependencies]
use std::time::Instant;
fn main() {
// Matrix size for the benchmarks
let rows = 500;
let cols = 500;
// Vector size must match the number of columns in the matrix for matrix-vector multiplication
let n = cols;
// Generate random vectors and matrices
let vec_a = DVector::from_element(n, 1.0); // Vector of size n filled with 1.0
let vec_b = DVector::from_element(n, 2.0); // Vector of size n filled with 2.0
let matrix_a = DMatrix::from_element(rows, cols, 1.0); // Matrix of size rows x cols filled with 1.0
let matrix_b = DMatrix::from_element(rows, cols, 2.0); // Matrix of size rows x cols filled with 2.0
// Benchmarking Vector addition
let start = Instant::now();
let _vec_add = &vec_a + &vec_b;
let duration = start.elapsed();
println!("Vector addition took: {:?}", duration);
// Benchmarking Vector dot product
let start = Instant::now();
let _dot_product = vec_a.dot(&vec_b);
let duration = start.elapsed();
println!("Vector dot product took: {:?}", duration);
// Benchmarking Matrix addition
let start = Instant::now();
let _matrix_add = &matrix_a + &matrix_b;
let duration = start.elapsed();
println!("Matrix addition took: {:?}", duration);
// Benchmarking Matrix multiplication
let start = Instant::now();
let _matrix_mul = &matrix_a * &matrix_b;
let duration = start.elapsed();
println!("Matrix multiplication took: {:?}", duration);
// Benchmarking Matrix inversion
let matrix_invertible = DMatrix::from_diagonal_element(rows, cols, 1.0); // Diagonal matrix for invertibility
let start = Instant::now();
let _matrix_inv = matrix_invertible.try_inverse();
let duration = start.elapsed();
println!("Matrix inversion took: {:?}", duration);
// Benchmarking Matrix-vector multiplication (now the vector size matches the matrix column size)
let start = Instant::now();
let _matrix_vec_mul = &matrix_a * &vec_a;
let duration = start.elapsed();
println!("Matrix-vector multiplication took: {:?}", duration);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment