-
-
Save sritchie/1627900 to your computer and use it in GitHub Desktop.
timing matrix multiplication
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
(defn feature-vec [n] | |
(map (partial cons 1) | |
(for [x (range n)] | |
(take 22 (repeatedly rand))))) | |
(defn dot-product [x y] | |
(reduce + (map * x y))) | |
(defn transpose | |
"returns the transposition of a `coll` of vectors" | |
[coll] | |
(apply map vector coll)) | |
(defn matrix-mult | |
[mat1 mat2] | |
(let [row-mult (fn [mat row] | |
(map (partial dot-product row) | |
(transpose mat)))] | |
(map (partial row-mult mat2) | |
mat1))) | |
(defn test-my-mult | |
[n afn] | |
(let [xs (feature-vec n) | |
xst (transpose xs)] | |
(time (dorun (afn xst xs))))) | |
;; Example (yields a 23x23 matrix): | |
;; (test-my-mult 1000 i/mmult) => "Elapsed time: 32.626 msecs" | |
;; (test-my-mult 10000 i/mmult) => "Elapsed time: 628.841 msecs" | |
;; (test-my-mult 1000 matrix-mult) => "Elapsed time: 14.748 msecs" | |
;; (test-my-mult 10000 matrix-mult) => "Elapsed time: 434.128 msecs" | |
;; (test-my-mult 1000000 matrix-mult) => "Elapsed time: 375751.999 msecs" | |
;; Test from wikipedia | |
;; (def A [[14 9 3] [2 11 15] [0 12 17] [5 2 3]]) | |
;; (def B [[12 25] [9 10] [8 5]]) | |
;; user> (matrix-mult A B) | |
;; ((273 455) (243 235) (244 205) (102 160)) | |
(require '[incanter.core :as i]) | |
;; user> (i/mmult A B) | |
;; [273.0000 455.0000 | |
;; 243.0000 235.0000 | |
;; 244.0000 205.0000 | |
;; 102.0000 160.0000] |
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
import numpy as np | |
def test_my_mult(n): | |
A = np.random.rand(n*23).reshape(n,23) | |
At = A.T | |
t0 = time.time() | |
res = np.dot(A.T, A) | |
print time.time() - t0 | |
print np.shape(res) | |
return res | |
# Example (returns a 23x23 matrix): | |
# >>> results = test_my_mult(1000000) | |
# | |
# 0.906938076019 | |
# (23, 23) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment