Last active
January 7, 2019 07:55
-
-
Save imbolc/dd0b439a7106ad621eaa1cf4df4a4152 to your computer and use it in GitHub Desktop.
Dot product on rust vs numpy
This file contains hidden or 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
import time | |
import numpy as np | |
tm = time.time() | |
size = 10000 | |
cycles = 100 | |
matrix = np.ones((size, size), dtype=int) | |
vector = np.array([-1 if x % 2 else 1 for x in range(size)]) | |
for i in range(cycles): | |
prod = matrix.dot(vector) | |
sum = prod.sum() | |
took = time.time() - tm | |
print(f"size: {size}, cycles: cycles, sum: {sum}, took: {took}") |
This file contains hidden or 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
fn main() { | |
let (size, cycles) = (10000, 100); | |
let matrix = vec![vec![1; size]; size]; | |
let vector = (0..size).map(|x| if x % 2 == 0 { 1 } else { -1 }).collect(); | |
let mut sum = 0; | |
for _ in 0..cycles { | |
let prod = dot_product(&matrix, &vector); | |
sum = prod.iter().sum(); | |
} | |
println!("size: {}, cycles: {}, sum: {}", size, cycles, sum); | |
} | |
fn dot_product(matrix: &Vec<Vec<i32>>, vector: &Vec<i32>) -> Vec<i32> { | |
let mut prod: Vec<i32> = Vec::with_capacity(vector.len()); | |
for row in matrix { | |
let mut cell = 0; | |
for (a, b) in row.iter().zip(vector.iter()) { | |
cell += a * b; | |
} | |
prod.push(cell); | |
} | |
prod | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment