Domanda

I have a function in python that basically takes the sign of an array (75,150), for example. I'm coming from Matlab and the time execution looks more or less the same less this function. I'm wondering if sign() works very slowly and you know an alternative to do the same.

Thx,

È stato utile?

Soluzione

I can't tell you if this is faster or slower than Matlab, since I have no idea what numbers you're seeing there (you provided no quantitative data at all). However, as far as alternatives go:

import numpy as np
a = np.random.randn(75, 150)
aSign = np.sign(a)

Testing using %timeit in IPython:

In [15]: %timeit np.sign(a)
10000 loops, best of 3: 180 µs per loop

Because the loop over the array (and what happens inside it) is implemented in optimized C code rather than generic Python code, it tends to be about an order of magnitude faster—in the same ballpark as Matlab.


Comparing the exact same code as a numpy vectorized operation vs. a Python loop:

In [276]: %timeit [np.sign(x) for x in a]
1000 loops, best of 3: 276 us per loop

In [277]: %timeit np.sign(a)
10000 loops, best of 3: 63.1 us per loop

So, only 4x as fast here. (But then a is pretty small here.)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top