user2939212
user2939212

Reputation: 405

Why Matlab matrix inversion is faster than numpy?

This is related to several questions that discuss the speed of numpy vs Matlab. However most of them have several matrix operations than a single operation. E.g. Difference on performance between numpy and matlab

For me, the time numpy take just to invert a random matrix is approximately 5 times slower than that of matlab.

Here is the matlab script,

N = 1000;

B = randn(N,N);
h = tic;
T = 40;
for i=1:40

    Rinv = (B)^(-1);
end
toc(h)/40

This gives an average values of 0.08 seconds approximately.

While this python script gives 0.4 seconds (approx).

import numpy as np 
from numpy import linalg as LA
import time 

N=1000
R = np.random.random((N,N))
T=40

t1 = time.clock()
for i in range(0,T):
    Rinv = LA.inv(R)
t2 = time.clock()
print 'avg time for inverse ',(t2-t1)/T

Is there any reason for this, or anyway to improve python performance ? I have already implemented my work on Python and I am worried whether I will have to port all my code to matlab. I am working on Ubuntu 16.04, Python 2.7, Matlab R2016b.

I have read that the time is not a good module for execution time comparisons, I feel this is something more than that.

Upvotes: 1

Views: 1737

Answers (1)

B. M.
B. M.

Reputation: 18628

On my computer (Windows, python 3.5, numpy 1.11.2) :

In [6]: %timeit inv(a)
10 loops, best of 3: 86 ms per loop

edit:

or, without Ipython:

>>>timeit.timeit('inv(a)','from __main__ import inv,a',number=100)/100

which is similar to Matlab.

to know what code is used in the background, check it :

In [12]: np.__config__.show() 
blas_mkl_info:
include_dirs = ['c:/users/bruno/miniconda3\\Library\\include']
libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
...

Upvotes: 4

Related Questions