Why is numpy's exp slower than Matlab? How to make it faster?

Viewed 1686

I have a pretty simple example which shows that NumPy's np.exp is about 10x slower than Matlab. How can I speed up Python? I'm running 32bit Python 2.7, NumPy version 1.11.3, and numpy is using the MKL blas & lapack libraries.

Also, the difference in time is so large that I don't think the timing mechanism is having a big effect.

Code example in Python:

import numpy as np
import timeit

setup='import numpy as np; import numexpr as ne; n=100*1000; a = np.random.uniform(size=n)'
time = timeit.timeit('b=np.exp(a)', setup=setup, number=1000)
print 'Time for 1000 (np.exp): ',time
time = timeit.timeit('b=ne.evaluate("exp(a)")', setup=setup, number=1000)
print 'Time for 1000 (numexpr): ',time

Results in:

Time for 1000 (np.exp):  2.25906916167
Time for 1000 (numexpr):  0.591470532849

In Matlab:

a = rand([100*1000,1]);
times = [];
for i=1:1000,
    tic
    b = exp(a);
    t=toc;
    times(i) = t;
end

fprintf('Time for 1000: %f\n',sum(times));

Resulting in:

Time for 1000: 0.268527
1 Answers
Related