The future of Python immutability

sturlamolden sturlamolden at yahoo.no
Fri Sep 4 23:48:13 EDT 2009


On 5 Sep, 05:12, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:

> Is the difference because of mutability versus immutability, or because
> of C code in Numpy versus Matlab code? Are you comparing bananas and
> pears?


It consisted of something like this


import numpy

def D4_Transform(x, s1=None, d1=None, d2=None):
    C1 = 1.7320508075688772
    C2 = 0.4330127018922193
    C3 = -0.066987298107780702
    C4 = 0.51763809020504137
    C5 = 1.9318516525781364
    if d1 == None:
       d1 = numpy.zeros(x.size/2)
       s1 = numpy.zeros(x.size/2)
       d2 = numpy.zeros(x.size/2)
    odd = x[1::2]
    even = x[:-1:2]
    d1[:] = odd[:] - C1*even[:]
    s1[:-1] = even[:-1] + C2*d1[:-1] + C3*d1[1:]
    s1[-1] = even[-1] + C2*d1[-1] + C3*d1[0]
    d2[0] = d1[0] + s1[-1]
    d2[1:] = d1[1:] + s1[:-1]
    even[:] = C5 * s1[:]
    odd[:] = C4 * d2[:]
    if x.size > 2:
    D4_Transform(even,s1[0:even.size/2],
            d1[0:even.size/2],d2[0:even.size/2])


against Matlab:

function x = D4_Transform(x)
   C1 =  1.7320508075688772;
   C2 =  0.4330127018922193;
   C3 = -0.066987298107780702;
   C4 =  0.51763809020504137;
   C5 =  1.9318516525781364;
   s1 = zeros(ceil(size(x)/2));
   d1 = zeros(ceil(size(x)/2));
   d2 = zeros(ceil(size(x)/2));
   odd = x(2:2:end);
   even = x(1:2:end-1);
   d1(:) = odd - C1*even;
   s1(1:end-1) = even(1:end-1) + C2*d1(1:end-1) + C3*d1(2:end);
   s1(end) = even(end) + C2*d1(end) + C3*d1(1);
   d2(1) = d1(1) + s1(end);
   d2(2:end) = d1(2:end) + s1(1:end-1);
   x(1:2:end-1) = C5*s1;
   x(2:2:end) = C4*d2;
   if (length(x) > 2)
      x(1:2:end-1) = D4_Transform(x(1:2:end-1));
   end


I wasn't comparing bananas against pears. Mathworks informed me they
were using my code to investigate why Matlab was showing such slow-
downs. I am not sure what they found out, eventially. I have also
wondered if immutability vs. mutability was the reason, as NumPy
generates temporary arrays. But I have not found a better explanation
either. Anyhow, ~30 seconds for Matlab vs. ~3 seconds for Python is a
major difference. (After I did this test, Matlab has acquired a JIT
compiler which might change the timings. I haven't tested as I don't
have access to it.)


Sturla Molden






More information about the Python-list mailing list