in reply to PDL vs C speed question

You can reduce the number of math ops and save some time. It won't make the Perl compete with the C, but you can apply the same optimization to the C, and make it that much faster. Basically, I'm factoring the multiplication out of the inner loop. The division can be done after all the looping.
for my $i (0..$#data){ my $sum_j = 0; $sum_j += $data[$_] for $i..$#data; $pears += $data[$i] * $sum_j; }
This was about 3x faster than (my interpretation of) your original, for me. Some of that comes from changing the looping constructs, but a chunk of it comes from fewer math ops.

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: PDL vs C speed question
by glwtta (Hermit) on May 07, 2005 at 23:58 UTC
    I don't think I understand your code - is @data the same as my @data?

    I think what's confusing people here is the PDL notation - my fault, I should've given the pure Perl version - since $data[$i] and $data[$j] are PDL vectors, the '*' operator is overloaded to return a vector of the same length as its arguments, with every component being the product of the corresponding components of the input vectors. The sum() function simply returns the sum of the vector components.

    The Perl version of my C example would look like this, assuming @data is an array of arrayrefs, rather than an array of PDL vectors:

    for ($i = 0; i < @data; $i++) { for($j = $i + 1; $j < @data; $j++) { my $sum = 0; $sum += $data[$i][$_] * $data[$j][$_] for(0..@{$data[$i]}-1); my $pears = $sum / @{$data[$i]}; } }
    I really don't think the math here can be simplified any more; or else I need to brush up on basic arithmetic :)

    minor edit: forgot that square brackets get interpreted