[Numpy-discussion] problem with vectorized difference equation
Francesco Barale
francesco.barale at gmail.com
Fri Apr 6 19:27:53 EDT 2012
Now I am clear. I guess the vectorized notation speeds up difference
equations describing FIR structures, whereas IIR ones won't benefit.
Francesco Barale wrote:
>
> Hello everyone,
>
> After reading the very good post
> http://technicaldiscovery.blogspot.com/2011/06/speeding-up-python-numpy-cython-and.html
> and the book by H. P. Langtangen 'Python scripting for computational
> science' I was trying to speed up the execution of a loop on numpy arrays
> being used to describe a simple difference equation.
>
> The actual code I am working on involves some more complicated equations,
> but I am having the same exact behavior as described below. To test the
> improvement in speed I wrote the following in vect_try.py:
>
> #!/usr/bin/python
> import numpy as np
> import matplotlib.pyplot as plt
>
> dt = 0.02 #time step
> time = np.arange(0,2,dt) #time array
> u = np.sin(2*np.pi*time) #input signal array
>
> def vect_int(u,y): #vectorized function
> n = u.size
> y[1:n] = y[0:n-1] + u[1:n]
> return y
>
> def sc_int(u,y): #scalar function
> y = y + u
> return y
>
> def calc_vect(u, func=vect_int):
> out = np.zeros(u.size)
> for i in xrange(u.size):
> out = func(u,out)
> return out
>
> def calc_sc(u, func=sc_int):
> out = np.zeros(u.size)
> for i in xrange(u.size-1):
> out[i+1] = func(u[i+1],out[i])
> return out
>
> To verify the execution time I've used the timeit function in Ipython:
>
> import vect_try as vt
> timeit vt.calc_vect(vt.u) --> 1000 loops, best of 3: 494 us per loop
> timeit vt.calc_sc(vt.u) -->10000 loops, best of 3: 92.8 us per loop
>
> As you can see the scalar implementation looping one item at the time
> (calc_sc) is 494/92.8~5.3 times faster than the vectorized one
> (calc_vect).
>
> My problem consists in the fact that I need to iterate the execution of
> vect_int in order for it to operate on all the elements of the input
> array. If I execute vect_int only once, it will only operate on the first
> slice of the vectors leaving the remaining untouched. My understanding was
> that the vector expression y[1:n] = y[0:n-1] + u[1:n] was supposed to
> iterate over all the array, but that's not happening for me. Can anyone
> tell me what I am doing wrong?
>
> Thanks!
> Francesco
>
>
--
View this message in context: http://old.nabble.com/problem-with-vectorized-difference-equation-tp33641688p33646154.html
Sent from the Numpy-discussion mailing list archive at Nabble.com.
More information about the NumPy-Discussion
mailing list