Skip to Main Content Skip to Search
Login
File Exchange
MATLAB Newsgroup
Link Exchange
  Blogs  
 Contest 
MathWorks.com

Thread Subject: vectorized computation in C++ such as those in Matlab (Matlab to

Subject: vectorized computation in C++ such as those in Matlab (Matlab to

From: Luna Moon

Date: 22 Jul, 2008 14:08:38

Message: 1 of 24

Dear all,

Can C++/STL/Boost do the vectorized calculation as those in Matlab?

For example, in the following code, what I really want to do is to
send in a vector of u's.

All other parameters such as t, l1, l2, l3, etc. are scalars...

But u is a vector.

Thus, t6 becomes a vector.

t9 is an element-wise multiplication...

The following code was actually converted from Matlab.

If vectorized computation is not facilitated, then I have to call this
function millions of times.

But if vectorized computation is okay, then I can send in just a u
vector with batch elements a time.

I have many such code in Matlab need to be converted into C++ with
vectorization.

Any thoughts?

Thank you!

double t5, t6, t7, t9, t11, t13, t16, t20, t23, t27, t32, t34, t36,
t37, t38, t42,
t44, t47, t48, t51, t52, t54, t59, t60, t61, t66, t67, t69, t74,
t75, t76, t81,
t82, t84, t87, t105, t106, t110, t112;

t5 = exp(-t * l1 - t * l2 - t * l3);
t6 = t * u;
t7 = mu1 * mu1;
t9 = u * u;
t11 = kappa * kappa;
t13 = 0.1e1 / (t9 * t7 + t11);

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: Leandro Melo

Date: 22 Jul, 2008 15:00:51

Message: 2 of 24

> Dear all,
>
> Can C++/STL/Boost do the vectorized calculation as those in Matlab?
>
> For example, in the following code, what I really want to do is to
> send in a vector of u's.
>
> All other parameters such as t, l1, l2, l3, etc. are scalars...
>
> But u is a vector.
>
> Thus, t6 becomes a vector.
>
> t9 is an element-wise multiplication...
>
> The following code was actually converted from Matlab.
>
> If vectorized computation is not facilitated, then I have to call this
> function millions of times.
>
> But if vectorized computation is okay, then I can send in just a u
> vector with batch elements a time.
>
> I have many such code in Matlab need to be converted into C++ with
> vectorization.
>
> Any thoughts?
>
> Thank you!
>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 double t5, t6, t7, t9, t11, t13, t16, t20=
, t23, t27, t32, t34, t36,
> t37, t38, t42,
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t44, t47, t48, t51, t52, =
t54, t59, t60, t61, t66, t67, t69, t74,
> t75, t76, t81,
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t82, t84, t87, t105, t106=
, t110, t112;
>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t5 =3D exp(-t * l1 - t * l2 - t * l3);
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t6 =3D t * u;
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t7 =3D mu1 * mu1;
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t9 =3D u * u;
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t11 =3D kappa * kappa;
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t13 =3D 0.1e1 / (t9 * t7 + t11);

Hi.

I think matlab provides a c++ api. Have you checked it out? There's
also the matrix template library for general algebra computations. You
might find it useful.


--
Leandro T. C. Melo

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: Steve Amphlett

Date: 22 Jul, 2008 15:20:05

Message: 3 of 24

Luna Moon <lunamoonmoon@gmail.com> wrote in message
<e0f8d278-54bf-4826-bcca-
bbbd88bfaec6@79g2000hsk.googlegroups.com>...
> Dear all,
>
> Can C++/STL/Boost do the vectorized calculation as those
in Matlab?
>
> For example, in the following code, what I really want to
do is to
> send in a vector of u's.
>
> All other parameters such as t, l1, l2, l3, etc. are
scalars...
>
> But u is a vector.
>
> Thus, t6 becomes a vector.
>
> t9 is an element-wise multiplication...
>
> The following code was actually converted from Matlab.
>
> If vectorized computation is not facilitated, then I have
to call this
> function millions of times.
>
> But if vectorized computation is okay, then I can send in
just a u
> vector with batch elements a time.
>
> I have many such code in Matlab need to be converted into
C++ with
> vectorization.
>
> Any thoughts?
>
> Thank you!
>
> double t5, t6, t7, t9, t11, t13, t16, t20,
t23, t27, t32, t34, t36,
> t37, t38, t42,
> t44, t47, t48, t51, t52, t54, t59,
t60, t61, t66, t67, t69, t74,
> t75, t76, t81,
> t82, t84, t87, t105, t106, t110,
t112;
>
> t5 = exp(-t * l1 - t * l2 - t * l3);
> t6 = t * u;
> t7 = mu1 * mu1;
> t9 = u * u;
> t11 = kappa * kappa;
> t13 = 0.1e1 / (t9 * t7 + t11);

Write some Matrix algebra classes with overloaded operators
that mimic Matlab's behaviour. Then you'll find code
conversion becomes simple.

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: Luna Moon

Date: 22 Jul, 2008 15:38:21

Message: 4 of 24

I don't think Matlab's C++ API can do that. I think it is just a C
interface. It does not have STL, Boost etc.

Also, we are not talking about things as complicated as high speed
matrix computation, it's just vectorized computation...

On Jul 22, 11:00=A0am, Leandro Melo <ltcm...@gmail.com> wrote:
> > Dear all,
>
> > Can C++/STL/Boost do the vectorized calculation as those in Matlab?
>
> > For example, in the following code, what I really want to do is to
> > send in a vector of u's.
>
> > All other parameters such as t, l1, l2, l3, etc. are scalars...
>
> > But u is a vector.
>
> > Thus, t6 becomes a vector.
>
> > t9 is an element-wise multiplication...
>
> > The following code was actually converted from Matlab.
>
> > If vectorized computation is not facilitated, then I have to call this
> > function millions of times.
>
> > But if vectorized computation is okay, then I can send in just a u
> > vector with batch elements a time.
>
> > I have many such code in Matlab need to be converted into C++ with
> > vectorization.
>
> > Any thoughts?
>
> > Thank you!
>
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 double t5, t6, t7, t9, t11, t13, t16, t=
20, t23, t27, t32, t34, t36,
> > t37, t38, t42,
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t44, t47, t48, t51, t52=
, t54, t59, t60, t61, t66, t67, t69, t74,
> > t75, t76, t81,
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t82, t84, t87, t105, t1=
06, t110, t112;
>
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t5 =3D exp(-t * l1 - t * l2 - t * l3);
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t6 =3D t * u;
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t7 =3D mu1 * mu1;
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t9 =3D u * u;
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t11 =3D kappa * kappa;
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t13 =3D 0.1e1 / (t9 * t7 + t11);
>
> Hi.
>
> I think matlab provides a c++ api. Have you checked it out? There's
> also the matrix template library for general algebra computations. You
> might find it useful.
>
> --
> Leandro T. C. Melodt





Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: Rune Allnor

Date: 22 Jul, 2008 15:54:14

Message: 5 of 24

On 22 Jul, 16:08, Luna Moon <lunamoonm...@gmail.com> wrote:
> Dear all,
>
> Can C++/STL/Boost do the vectorized calculation as those in Matlab?

No. The computations are done element-wise, but you can write wrapper
functions which let you as user view things as vector operations.

> For example, in the following code, what I really want to do is to
> send in a vector of u's.
...
> If vectorized computation is not facilitated, then I have to call this
> function millions of times.
>
> But if vectorized computation is okay, then I can send in just a u
> vector with batch elements a time.

I assume you have a few million elements you want to send as argument
to the computations, and that each operation on a scalar will produce
a scalar result. So the vector is only a container for the input and
output data. Here is an example on how to do things (not a complete
program):

#include <vector> // You need this one to use the
vector class
#include <math> // You need this to get access to
some
                                  // maths functions
std::vector<double> input; // Declare a vector for the input

double myfunction(double x)
{
  // Implement your computations here, e.g.
  y=sin(x);
}

std::vector<double> myfunction(std::vector<double> x)
{
    // Wrapper function that lets you call the function
    // for each element in a vector

    std::vector<double> y; // Declare the vector for results
    y.reserve(x.size()); // You already know how many elements y
                            // needs to hold, so reserve the space
                            // up front

    for (int n=0;n<x.size();++n) // Now the loop.
    {
        y[n]=myfunction(x[n]); // Note the same name on the
functions!
    }
    return y;
}

and there you are. When you want to use this you just write

    std::vector<double> x;
    // Initialize x
    std::vector<double> y = myfunction(x);

as you would in matlab. You just tell the compiler what you want and
the compiler is assigned the task of picking exactly which variant
of 'myfunction' is used, based on the type of the argument you
call it with.

Try this:

    std::vector<double> x;
    // Initialize x
    std::vector<double> y = myfunction(x);
    double a = 3.14;
    double b;
    b = myfunction(a);

Two functions with the same name are used, but since the argument
types are different, the compiler figures out which variant to
use in each case.

Rune

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: Rune Allnor

Date: 22 Jul, 2008 15:59:06

Message: 6 of 24

On 22 Jul, 17:54, Rune Allnor <all...@tele.ntnu.no> wrote:

Saw a typo just after I sent the first message...

> double myfunction(double x)
> {
> =A0 // Implement your computations here, e.g.
> =A0 y=3Dsin(x);
    return (y); // << =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D Missed thi=
s line....
> }

Rune

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab

From: Lionel B

Date: 22 Jul, 2008 16:37:22

Message: 7 of 24

On Tue, 22 Jul 2008 07:08:38 -0700, Luna Moon wrote:

> Dear all,
>
> Can C++/STL/Boost do the vectorized calculation as those in Matlab?

What exactly do you mean by "vectorized calculation as those in Matlab"?
Do you just mean that Matlab has a native vector type and does
calculations with it, or were you suggesting that Matlab processes
vectors in some special way that C++ cannot?

Matlab, AFAIK, does a lot of its matrix/vector arithmetic, such as dot
products and matrix-matrix or matrix-vector multiplication, using a BLAS
library - that is highly optimised linear algebra code (generally written
in Fortran) - which is accessible via C++, since there is a well-defined
interface for C++ (C, really) and Fortran. There is a good chance you
will already have a BLAS library on your system; if not, there are open
source (e.g,. the ATLAS project) as well as vendor-supplied versions
(e.g. Intel, AMD, etc supply BLAS libraries).

It is possible that Matlab will also make use of very machine-specific
optimisations such as sse/mmx for floating point computation. You can use
these too from C++ if you can persuade your compiler to play ball.

The bottom line is that there's nothing Matlab can do that you can't do
in C++, equally (if not more) efficiently. It's more a question of
convenience: Matlab is designed specifically for vector/matrix
manipulation - C++ is a general-purpose programming language.

> For example, in the following code, what I really want to do is to send
> in a vector of u's.
>
> All other parameters such as t, l1, l2, l3, etc. are scalars...
>
> But u is a vector.
>
> Thus, t6 becomes a vector.
>
> t9 is an element-wise multiplication...
>
> The following code was actually converted from Matlab.
>
> If vectorized computation is not facilitated, then I have to call this
> function millions of times.
>
> But if vectorized computation is okay, then I can send in just a u
> vector with batch elements a time.

I'm really not quite sure what you mean here.

The closest thing in C++ to a Matlab vector is probably the
std::valarray<double> class, although it seems a bit of a bodge and hence
rather unpopular. The std::vector<double> class will probably do you
quite well; it doesn't implement functionality such as element-wise
multiplication, so you will have to do that yourself - but that's pretty
simple.

There are also various matrix/vector C++ libraries knocking around (e.g.
Blitz++) that you might want to look at.

In terms of efficiency, if you are doing a lot of large matrix
multiplications or more sophisticated linear algebra a la Matlab, then
you might want to investigate the BLAS and possibly LAPACK (Linear
Algebra Package), but I suspect that might be overkill in your case. And
it is ugly.

FWIW, I recently ported a lot of Matlab code to C++ and have to say that
C++ generally kicks Matlab's a*se in terms of efficiency - but not in
ease of coding (Matlab appears to suffer performance-wise from a lot of
internal copying which you can eliminate in hand-coded C++).

> I have many such code in Matlab need to be converted into C++ with
> vectorization.
>
> Any thoughts?
>
> Thank you!
>
> double t5, t6, t7, t9, t11, t13, t16, t20, t23, t27, t32,
t34, t36,
> t37, t38, t42,
> t44, t47, t48, t51, t52, t54, t59, t60, t61, t66,
t67, t69, t74,
> t75, t76, t81,
> t82, t84, t87, t105, t106, t110, t112;
>
> t5 = exp(-t * l1 - t * l2 - t * l3);
> t6 = t * u;
> t7 = mu1 * mu1;
> t9 = u * u;
> t11 = kappa * kappa;
> t13 = 0.1e1 / (t9 * t7 + t11);

--
Lionel B

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to C++)?

From: Bart van Ingen Schenau

Date: 22 Jul, 2008 16:36:31

Message: 8 of 24

Luna Moon wrote:

> Dear all,
>
> Can C++/STL/Boost do the vectorized calculation as those in Matlab?

I don't know what Boost has in the field of matrix & vector
computations, but standard C++ does not have anything even remotely
resembling the capabilities of Matlab.

The closest you can get with standard C++ is to use std::valarray<>,
which was intended to facilitate computations that can potentially be
executed in parallel.

Bart v Ingen Schenau
--
a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq
c.l.c FAQ: http://c-faq.com/
c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to C++)?

From: Steve Amphlett

Date: 23 Jul, 2008 08:08:01

Message: 9 of 24

Bart van Ingen Schenau <bart@ingen.ddns.info> wrote in
message <9740147.dvEKTklcxX@ingen.ddns.info>...
> Luna Moon wrote:
>
> > Dear all,
> >
> > Can C++/STL/Boost do the vectorized calculation as
those in Matlab?
>
> I don't know what Boost has in the field of matrix &
vector
> computations, but standard C++ does not have anything
even remotely
> resembling the capabilities of Matlab.
>
> The closest you can get with standard C++ is to use
std::valarray<>,
> which was intended to facilitate computations that can
potentially be
> executed in parallel.
>
> Bart v Ingen Schenau

I've always found it easier to define my own classes which
use STL vectors (etc) to store the data and have overloads
to work on the data (& sometimes specialised conversion
constructor to convert types). Operating directly on the
STL vectors in main code gets messy.

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: rocksportrocker

Date: 23 Jul, 2008 13:29:32

Message: 10 of 24

On 22 Jul., 16:08, Luna Moon <lunamoonm...@gmail.com> wrote:
> Dear all,
>
> Can C++/STL/Boost do the vectorized calculation as those in Matlab?
>
> For example, in the following code, what I really want to do is to
> send in a vector of u's.
>
> All other parameters such as t, l1, l2, l3, etc. are scalars...
>
> But u is a vector.
>
> Thus, t6 becomes a vector.
>
> t9 is an element-wise multiplication...
>
> The following code was actually converted from Matlab.
>
> If vectorized computation is not facilitated, then I have to call this
> function millions of times.
>
> But if vectorized computation is okay, then I can send in just a u
> vector with batch elements a time.
>
> I have many such code in Matlab need to be converted into C++ with
> vectorization.
>
> Any thoughts?
>
> Thank you!
>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 double t5, t6, t7, t9, t11, t13, t16, t20=
, t23, t27, t32, t34, t36,
> t37, t38, t42,
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t44, t47, t48, t51, t52, =
t54, t59, t60, t61, t66, t67, t69, t74,
> t75, t76, t81,
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t82, t84, t87, t105, t106=
, t110, t112;
>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t5 =3D exp(-t * l1 - t * l2 - t * l3);
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t6 =3D t * u;
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t7 =3D mu1 * mu1;
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t9 =3D u * u;
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t11 =3D kappa * kappa;
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 t13 =3D 0.1e1 / (t9 * t7 + t11);

Why do you want that ? Is it because the code is easier to read, or do
you hope
to get better performance ?

If it is for performance: Writing native loops in C/C++ with some
optimization flags
will give you best performance in most cases. Sometimes optimized BLAS
like
ATLAS will improve performance further.

Vectorized code in Matlab is faster than looping code, because in the
latter the
loops are interpreted which slows things down. Internally Matlab works
as described
above.

Greetings, Uwe

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: Bo Schwarzstein

Date: 25 Jul, 2008 01:20:52

Message: 11 of 24

On Jul 22, 10:08 pm, Luna Moon <lunamoonm...@gmail.com> wrote:
> Dear all,
>
> Can C++/STL/Boost do the vectorized calculation as those in Matlab?
>
> For example, in the following code, what I really want to do is to
> send in a vector of u's.
>
> All other parameters such as t, l1, l2, l3, etc. are scalars...
>
> But u is a vector.
>
> Thus, t6 becomes a vector.
>
> t9 is an element-wise multiplication...
>
> The following code was actually converted from Matlab.
>
> If vectorized computation is not facilitated, then I have to call this
> function millions of times.
>
> But if vectorized computation is okay, then I can send in just a u
> vector with batch elements a time.
>
> I have many such code in Matlab need to be converted into C++ with
> vectorization.
>
> Any thoughts?
>
> Thank you!
>
> double t5, t6, t7, t9, t11, t13, t16, t20, t23, t27, t32, t34, t36,
> t37, t38, t42,
> t44, t47, t48, t51, t52, t54, t59, t60, t61, t66, t67, t69, t74,
> t75, t76, t81,
> t82, t84, t87, t105, t106, t110, t112;
>
> t5 = exp(-t * l1 - t * l2 - t * l3);
> t6 = t * u;
> t7 = mu1 * mu1;
> t9 = u * u;
> t11 = kappa * kappa;
> t13 = 0.1e1 / (t9 * t7 + t11);

GSL,GNU Octave,boost

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to ?C++)?

From: William Ahern

Date: 27 Jul, 2008 01:29:16

Message: 12 of 24

Luna Moon <lunamoonmoon@gmail.com> wrote:
<snip>
> If vectorized computation is not facilitated, then I have to call this
> function millions of times.
>
> But if vectorized computation is okay, then I can send in just a u
> vector with batch elements a time.
>
> I have many such code in Matlab need to be converted into C++ with
> vectorization.
>
> Any thoughts?
>
> Thank you!
>
> double t5, t6, t7, t9, t11, t13, t16, t20, t23, t27, t32, t34, t36,
> t37, t38, t42,
> t44, t47, t48, t51, t52, t54, t59, t60, t61, t66, t67, t69, t74,
> t75, t76, t81,
> t82, t84, t87, t105, t106, t110, t112;
>
> t5 = exp(-t * l1 - t * l2 - t * l3);
> t6 = t * u;
> t7 = mu1 * mu1;
> t9 = u * u;
> t11 = kappa * kappa;
> t13 = 0.1e1 / (t9 * t7 + t11);

This is out of my element, but I have written some vector code in GCC, just
for my own edification. I'm not sure how you would translate the above
code... I don't exactly see the vectors, unless I'm misinterpreting. Anyhow:

http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Vector-Extensions.html#Vector-Extensions

It's exceedingly simple. ICC and MSC support similar, though incompatible
syntax. With GCC, make sure to manually specify -march, otherwise the
generator won't have access to SSE instructions (or whatever your platform
has).

The biggest initial syntax gotcha I encountered was initializing the vector;
the vector can be treated like an array, IIRC, but I encountered some
hangups. Second, GCC has to load all the SSE registers, and other sourcery I
wasn't acquainted with. There just seems like there'd be lots of headaches
keeping the pipeline chugging along, depending on your data set, and where
it comes from.

Also, I have no idea if the syntax carriers over to C++. And perhaps GCC can
already accomplish similar optimizations with valarrays. Either way, you'll
definitely want to use the latest GCC 4.3 version, which AFAIK is at the
moment king of the hill regarding auto-vectorization.

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: Giovanni Gherdovich

Date: 06 Aug, 2008 12:54:29

Message: 13 of 24

Hello,

my question is pretty much related to this topic so I continue
the thread instead of opening another one.
I'm a former Matlab coder and a wannabe C++ coder.

I've read about std::valarray<> in the Stroustrup's book
"The C++ Programming Language", discovering that some operators
(like the multiplication *), and some basic math functions
like sin and cos, are overloaded in order to behave very similar
to Matlab ones when dealing with valarrays (mainly, they act
component-wise).

I'm aware of Matlab "vectorization" techniques; I use them to
avoid for-loops.
But when I do that I _don't_ do linear algebra: I just do
component-wise operations between matrices, in order to
save Matlab from doing serial calls to the same routine (via for-
loops).
I dont't think such code gains anything from using BLAS or
similarities.
I mean: taking the inverse of a matrix is linear algebra,
but multiplying two vectors component-wise is just... multiplying.

rocksportrocker
> If it is for performance: Writing native loops in C/C++ with some
> optimization flags will give you best performance in most cases.

Best performance than Matlab, or best performance than
"vectorized" C++?

Rune Allnor:
> The problem is that users who only know matlab and no other
> programming languages are conditioned to believe that the
> problem lies with for-loops as such, and not with matlab.

My question:
When writing C++ code, do you thing I can have faster code
if I use std::valarray<> in "the Matlab way", instead
of using, say, std::vector<> and for-loops?

I must admit that this curiosity comes from my previous Matlab
experiences, when I used to think to for-loops as being the devil,
but from a naive point of view I can image that "vectorized"
operations on std::valarray<> are optimized by smart compilation
techniques... after all the programmer doesn't specify the
order with which the operation as to be done, like in a foor-loop...
Is this just fantasy?
--NOTE that the scenario I have in mind is a single core machine.

Regards,
Giovanni Gherdovich

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: Rune Allnor

Date: 06 Aug, 2008 13:27:42

Message: 14 of 24

On 6 Aug, 14:54, Giovanni Gherdovich
<gherdov...@students.math.unifi.it> wrote:
> Hello,
>
> my question is pretty much related to this topic so I continue
> the thread instead of opening another one.
> I'm a former Matlab coder and a wannabe C++ coder.
>
> I've read about std::valarray<> in the Stroustrup's book
> "The C++ Programming Language", discovering that some operators
> (like the multiplication *), and some basic math functions
> like sin and cos, are overloaded in order to behave very similar
> to Matlab ones when dealing with valarrays (mainly, they act
> component-wise).
>
> I'm aware of Matlab "vectorization" techniques; I use them to
> avoid for-loops.

That's a *matlab* problem. 'Vectorization' is a concept
exclusive to matlab, which historically was caused by
what I consider to be bugs in the matlab interpreter.

> But when I do that I _don't_ do linear algebra: I just do
> component-wise operations between matrices, in order to
> save Matlab from doing serial calls to the same routine (via for-
> loops).
> I dont't think such code gains anything from using BLAS or
> similarities.
> I mean: taking the inverse of a matrix is linear algebra,
> but multiplying two vectors component-wise is just... multiplying.
>
> rocksportrocker
>
> > If it is for performance: Writing native loops in C/C++ with some
> > optimization flags will give you best performance in most cases.
>
> Best performance than Matlab,

Depending on exactly what you do, matlab *can* get very
close to best-possible performance since it uses highly
tuned low-level libraries. If your operation is covered by
such a function, you might find it difficult to beat matlab.
If not, don't be surprised if C++ code beats matlab by
a factor 5-10 or more.

> or best performance than
> "vectorized" C++?

There is no such thing as 'vectorized C++.'

> Rune Allnor:
>
> > The problem is that users who only know matlab and no other
> > programming languages are conditioned to believe that the
> > problem lies with for-loops as such, and not with matlab.
>
> My question:
> When writing C++ code, do you thing I can have faster code
> if I use std::valarray<> in "the Matlab way", instead
> of using, say, std::vector<> and for-loops?

I don't know. I haven't used std::valarray<>. I know I have
seen some comment somewhere that std::valarray<> was an early
attempt at a standardized way to handle numbercrunching in C++,
which was, well, not quite as successful as one might have
whished for.

> I must admit that this curiosity comes from my previous Matlab
> experiences, when I used to think to for-loops as being the devil,
> but from a naive point of view I can image that "vectorized"
> operations on std::valarray<> are optimized by smart compilation
> techniques...

You would be surprised: There are for-loops at the core of all
those libraries, even the BLAS libraries matlab is based on.
There are smart compilation techniques involved, but to *optimize*
the for-loops, not to *eliminate* them.

> after all the programmer doesn't specify the
> order with which the operation as to be done, like in a foor-loop...

I wrote a sketch to illustrate how this is done in a previous
post in this thread, which was posted only to comp.soft-sys.matlab:

http://groups.google.no/group/comp.soft-sys.matlab/msg/2ab57a27d663e1fa?hl=no

As you can see, the 'vector' version myfunction(std::vector<double>)
calls the scalar version myfunction(double) in a for-loop. This is
essentially what is done in all the libraries you use, including
matlab.

The for-loops are at the core, and the smart compiler techniques
optimize the executable code to avoid any unnecessary run-time
overhead.

> Is this just fantasy?

You might want to have a look at the basic texts on modern C++.
Try "Accelerated C++" by Koenig & Moo, or "You can do it!" by
Glassborow. Or both.

Rune

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: dj3vande@csclub.uwaterloo.ca.invalid

Date: 06 Aug, 2008 17:37:47

Message: 15 of 24

In article <6d972a8d-8bc3-44d7-9a40-40044c35131c@x41g2000hsb.googlegroups.com>,
Rune Allnor <allnor@tele.ntnu.no> wrote:
>On 6 Aug, 14:54, Giovanni Gherdovich
><gherdov...@students.math.unifi.it> wrote:

>> I'm aware of Matlab "vectorization" techniques; I use them to
>> avoid for-loops.
>
>That's a *matlab* problem. 'Vectorization' is a concept
>exclusive to matlab, which historically was caused by
>what I consider to be bugs in the matlab interpreter.

To describe this property of matlab as "buggy" is inordinately harsh.

It's an inherent property of interpreters: If you're interpreting a
loop, you have to look at the loop condition code, and the loop
bookkeeping code, and the code inside the loop, every time through.
Unless you go out of your way to make this fast, you end up having to
do a lookup-decode-process for each of those steps.
Compiling to native code lets you do the lookup-decode at compile time,
and for typical loops only generates a few machine-code instructions
for the loop bookkeeping and condition checking, which substantially
reduces the total amount of work the processor is doing. But making an
interpreter clever enough to do interpreted loops that fast is a Much
Harder Problem.

(So, the answer to the OP's question is (as already noted): Don't worry
about vectorizing, write loops and ask the compiler to optimize it, and
you'll probably come close enough to Matlab's performance that you
won't be able to tell the difference.)

Since Matlab is targeting numerical work with large arrays anyways,
there's not much benefit to speeding up this part of the interpreter;
if the program is spending most of its time inside the large-matrix
code (which is compiled to native code, aggressively optimized by the
compiler, and probably hand-tuned for speed), then speeding up the
interpreter's handling of the loop won't gain you any noticeable
speedup anyways. If you're writing loopy code to do things Matlab has
primitives for, you're probably better off vectorizing it anyways,
since that will make it both clearer and faster.
So (unlike with general-purpose interpreted languages that don't have
primitives that replace common loop idioms) there's no real benefit to
speeding up the Matlab interpreter's loop handling, and there are
obvious costs (development time, increased complexity, more potential
for bugs), so there are good reasons not to bother.

If you do have code that doesn't fit Matlab's vectorization model, you
can always write it in C or Fortran and wrap it up in a Matlab FFI
wrapper; Matlab's FFI is not hard to use on the compiled-to-native-code
side, and looks exactly like a Matlab function on the Matlab code side,
so it's almost always the Right Tool For The Job in that case.
(At my day job, I've been asked to do this for the Matlab programmers a
few times, and for hard-to-vectorize loopy code getting a speedup of
two or three orders of magnitude just by doing a reasonably direct
translation into C and compiling to native code with an optimizing
compiler is pretty much expected.)



dave

--
Dave Vandervies dj3vande at eskimo dot com
Erm... wouldn't clock(), used with Bill Godfrey's follow-up, ignoring my
follow-up to him (as suggested in your follow-up to me), do the trick
quite nicely? --Joona I Palaste in comp.lang.c

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: Rune Allnor

Date: 06 Aug, 2008 18:01:27

Message: 16 of 24

On 6 Aug, 19:37, dj3va...@csclub.uwaterloo.ca.invalid wrote:
> In article <6d972a8d-8bc3-44d7-9a40-40044c351...@x41g2000hsb.googlegroups=
.com>,
> Rune Allnor =A0<all...@tele.ntnu.no> wrote:
>
> >On 6 Aug, 14:54, Giovanni Gherdovich
> ><gherdov...@students.math.unifi.it> wrote:
> >> I'm aware of Matlab "vectorization" techniques; I use them to
> >> avoid for-loops.
>
> >That's a *matlab* problem. 'Vectorization' is a concept
> >exclusive to matlab, which historically was caused by
> >what I consider to be bugs in the matlab interpreter.
>
> To describe this property of matlab as "buggy" is inordinately harsh.

Here is a test example I first made ten years ago:

http://groups.google.no/group/comp.soft-sys.matlab/msg/e9699dcd19dcbe49?hl=
=3Dno

Do you think an interpreter overhead on the order of 100-200x
is acceptable? Note that in recent versions of matlab the same
example is only 5-10 slower than compiled code. I don't know
what has changed, but that sort of improvement is almost
certainly not possible unless there were one or more serious
bugs there in the first place.

Rune

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: dj3vande@csclub.uwaterloo.ca.invalid

Date: 07 Aug, 2008 03:34:10

Message: 17 of 24

In article <cad30e01-6396-479d-ad51-ae01abb0e49e@34g2000hsh.googlegroups.com>,
Rune Allnor <allnor@tele.ntnu.no> wrote:
>On 6 Aug, 19:37, dj3va...@csclub.uwaterloo.ca.invalid wrote:
>> In article
><6d972a8d-8bc3-44d7-9a40-40044c351...@x41g2000hsb.googlegroups.com>,
>> Rune Allnor <all...@tele.ntnu.no> wrote:

>> >That's a *matlab* problem. 'Vectorization' is a concept
>> >exclusive to matlab, which historically was caused by
>> >what I consider to be bugs in the matlab interpreter.
>>
>> To describe this property of matlab as "buggy" is inordinately harsh.
>
>Here is a test example I first made ten years ago:
>
>http://groups.google.no/group/comp.soft-sys.matlab/msg/e9699dcd19dcbe49?hl=no

So you can, by deliberately avoiding features that are in the language
and run in vanishingly small amounts of time, write code that exercises
the interpreter in ways that slow it down.

Do you write your own matrix multiplication code too?


>Do you think an interpreter overhead on the order of 100-200x
>is acceptable?

It depends on how the interpreter is used and how difficult it is to
avoid the overhead in cases where speed matters.
For Matlab? Certainly, especially since it's often trivial and rarely
difficult to run compiled-to-native code from the interpreter in cases
where it matters. The language is built as an interpreted shell that
calls native-code routines for primitives like matrix multiplication,
and when most of the running time in basic code is inside the primitives
anyways, when you want less-basic operations it makes sense to work
with the model that you already have - it's not broken.
If you really want to do something inside Matlab that doesn't reduce
nicely to primitives that are already in the language, you can always
write your own native code routine and call it from the interpreter.
Matlab's FFI is easy to use on the foreign side and completely
transparent on the Matlab side, so there's no good reason not to use
it.
(Of course, if what you're really trying to accomplish is writing loops
that run as fast as possible, you should be using Fortran anyways.
There's a reason we have more than one programming language.)


Exercise for the reader:
A native-code sum loop can be written in four instructions with one
cache-friendly memory access per iteration:
--------
top:
    addl (%ebx,%edx,4),%eax
    incl %edx
    cmpl %edx,%ecx
    jne top
--------
Write an interpreter that can run a comparable interpreted loop using
fewer than 400-800 instructions per iteration. Keep in mind that
memory access is expensive; cache misses (including for interpreter
code) count as no less than a few dozen instructions and possibly a few
hundred.


> Note that in recent versions of matlab the same
>example is only 5-10 slower than compiled code. I don't know
>what has changed, but that sort of improvement is almost
>certainly not possible unless there were one or more serious
>bugs there in the first place.

Bullshit. There are plenty of good reasons why it might have improved
that much without having any bugs, or even bad engineering tradeoffs,
in the original version.

It's not beyond the realm of possibility that hardware capabilities
have increased in ways that disproportionately affect interpreted code,
even without any changes to the Matlab system. (Or, depending on how
carefully you did your measurements, possibly the only thing that's
changed is that setup and measurement overhead are now big enough to
skew the numbers).

A more likely effect of increasing hardware capabilities is that
interpreter cleverness like pre-compiling to bytecode became
cost-effective. When you have a slow computer running interpreted code
that's mostly calls into primitives implemented as well-tuned native
code, the additional startup cost of making the interpreter cleverer
might be near-impossible to make up in improved running times once it's
started, but if the same startup cost happens ten or twenty times as
fast, it could very well fall below the threshold of what people
notice, and thereby become worth doing.

Another possible motivation for interpreter improvements is that the
primitives have improved (because of better tuning and/or new processor
instructions that can run them faster) to the point where the
interpreter speed actually makes a noticeable effect on properly
written code, which increases the benefits of improving it to the point
where they exceed the costs of doing so.

It's also not impossible that one of the motivations behind improving
it was that the Matlab people got sick of listening to idiots who can't
tell the difference between a hammer and a screwdriver whinging about
how hard it was to pound in nails with their screwdriver, and decided
that it was easier to add nail-pounding capabilities than to continue
to deal with the complaints.


And that's just off the top of my head; people who actually build and
work with interpreters could probably give you a rather longer list.


dave

--
Dave Vandervies dj3vande at eskimo dot com
>[An] optimizing compiler is no substitute for a good programmer
A good programmer is also no substitute for an optimizing compiler.
               --Nils O. Selesdal and Keith Thompson in comp.lang.c

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: Rune Allnor

Date: 07 Aug, 2008 08:42:04

Message: 18 of 24

On 7 Aug, 05:34, dj3va...@csclub.uwaterloo.ca.invalid wrote:
> In article <cad30e01-6396-479d-ad51-ae01abb0e...@34g2000hsh.googlegroups.=
com>,
> Rune Allnor =A0<all...@tele.ntnu.no> wrote:
>
> >On 6 Aug, 19:37, dj3va...@csclub.uwaterloo.ca.invalid wrote:
> >> In article
> ><6d972a8d-8bc3-44d7-9a40-40044c351...@x41g2000hsb.googlegroups.com>,
> >> Rune Allnor =A0<all...@tele.ntnu.no> wrote:
> >> >That's a *matlab* problem. 'Vectorization' is a concept
> >> >exclusive to matlab, which historically was caused by
> >> >what I consider to be bugs in the matlab interpreter.
>
> >> To describe this property of matlab as "buggy" is inordinately harsh.
>
> >Here is a test example I first made ten years ago:
>
> >http://groups.google.no/group/comp.soft-sys.matlab/msg/e9699dcd19dcbe...
>
> So you can, by deliberately avoiding features that are in the language
> and run in vanishingly small amounts of time, write code that exercises
> the interpreter in ways that slow it down.
>
> Do you write your own matrix multiplication code too?
>
> >Do you think an interpreter overhead on the order of 100-200x
> >is acceptable?
>
> It depends on how the interpreter is used and how difficult it is to
> avoid the overhead in cases where speed matters.
> For Matlab? =A0Certainly, especially since it's often trivial and rarely
> difficult to run compiled-to-native code from the interpreter in cases
> where it matters. =A0

It seems you might not be aware how matlab is used these days.
For the last decade or so the focus has veered from "Matrix
laboraory" to "scientific computing language." People use
matlab not as the "MATrix LABoratory" it was originally
designed to be, but as a development environment and
programming language on a par with Java.

In my day job I have met people who used poorly implemented
matlab code at key points in their business, only to find
that where matlab is used is a bankrupcy-inducing bottleneck.

The data processing took so long that only the benevolence
from their main customer kept them in business - 99% of
customers would have claimed violation of contract and
sued for damage reimbursements.

When I showed the processors the test, every single one of
them went a whiter shade of pale, "I though matlab was the
absolutely best there was!"

> The language is built as an interpreted shell that
> calls native-code routines for primitives like matrix multiplication,
> and when most of the running time in basic code is inside the primitives
> anyways, when you want less-basic operations it makes sense to work
> with the model that you already have - it's not broken.

The matlab engine has two parts: The parser and the interpreter.
The parser checks for syntax, undeclared variables and those
sorts of things. The interpreter translates code that passed
parser into executable statements. Both steps must necesarily
introduce run-time overhead compared to compiled code, I have
no issue with that.

But do take another look at the code I posted: What on earth
could cause an interpreter overhead of ~150x in that simple
code?

One possible answer - and I have no if this is how things is
done presently or if they were done like this in the past - is
that the code inside the for-loop is parsed and interpreted
everey single time the interpreter enters the loop. The same
piece of code which doesn't change during execution is
interpreted 100000000 times.

Why is that acceptable to you? Once the code has been checked
by the parser, the inerpreter ought to know all the blocks
of code present. There is no need to interpret the code inside
that for-loop more than once. It will not change during the
execution of the script.

This is a very simple argument which *might* have been the
cause of the traditionally poor performance of matlab with
loops. Whether this is a 'bug' or a 'poor design' is a
matter of semantics; the damage has been done over the past
couple of decades, as students who try and learn programming
with matlab as their first language have been conditioned to
believe that 'for-loops are evil.'

Rune

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: Rune Allnor

Date: 07 Aug, 2008 10:04:52

Message: 19 of 24

On 7 Aug, 05:34, dj3va...@csclub.uwaterloo.ca.invalid wrote:
> In article <cad30e01-6396-479d-ad51-ae01abb0e...@34g2000hsh.googlegroups.=
com>,

> It's also not impossible that one of the motivations behind improving
> it was that the Matlab people got sick of listening to idiots who can't
> tell the difference between a hammer and a screwdriver whinging about
> how hard it was to pound in nails with their screwdriver, and decided
> that it was easier to add nail-pounding capabilities than to continue
> to deal with the complaints.

This may certainly have been a contributing factor, but if you look
into the history of matlab you will find that it is in fact the other
way around: For the past 15 years or so The Mathworks have purposedly
expanded the target customer base from traditional educational
and R&D institutions to the general computer industry.

The main slogan in the marketing material from 1995 vintage matlab 4
was 'rapid prototyping.' On the printed material accompanying my 2005
vintage matlab release, the keywords on the front page are:

 - Computation
 - Visualization
 - Programming
 - Modeling
 - Simulation
 - Implementation

No hint about 'development' or 'prototyping.' An unsuspecting
customer meeting matlab for the first time might very well
interpret this as if matlab is a tool for designing and
implementing production code.

If you go to today's on-line product description at

http://www.mathworks.com/products/matlab/description1.html

there is an item for "Developing algorithms and applications"
which is about the only clue to matlab's origins as a developer's
tool. I find the term 'rapid prototyping' buried deep in an
online page on 'Programming and Application Development':

http://www.mathworks.com/applications/tech_computing/description/progapp.ht=
ml

Some cut'n paste from that page:

"The MATLAB=AE environment is well suited to rapid prototyping and
application development."

We already agreed about matlab as a prototyping tool. For some
reason I think matlab being presented as a tool for 'application
development' might come as a surprise to you.

Another one from the same page:

"MATLAB is the most productive development environment for creating
scientific and engineering applications because it offers powerful
tools for every step in the process to reduce your overall
development time."

Again, a definite (and maybe surprising) focus on *applications*,
not *prototypes*. And of course, it is the misplaced focus on
*development* time, not *run* time, which leaves the unsuspecting
down-the-line customers who use matlab-based applications in their
time-critical productions lines, hanging high and dry.

Rune

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: Uwe Schmitt

Date: 07 Aug, 2008 14:37:25

Message: 20 of 24

 Giovanni Gherdovich schrieb:
> Hello,
>
> my question is pretty much related to this topic so I continue
> the thread instead of opening another one.
> I'm a former Matlab coder and a wannabe C++ coder.
>
> I've read about std::valarray<> in the Stroustrup's book
> "The C++ Programming Language", discovering that some operators
> (like the multiplication *), and some basic math functions
> like sin and cos, are overloaded in order to behave very similar
> to Matlab ones when dealing with valarrays (mainly, they act
> component-wise).
>
> I'm aware of Matlab "vectorization" techniques; I use them to
> avoid for-loops.
> But when I do that I _don't_ do linear algebra: I just do
> component-wise operations between matrices, in order to
> save Matlab from doing serial calls to the same routine (via for-
> loops).
> I dont't think such code gains anything from using BLAS or
> similarities.
> I mean: taking the inverse of a matrix is linear algebra,
> but multiplying two vectors component-wise is just... multiplying.
>
yes. but you can do some enrollment or other
access patterns for optimizing cache access.
this is a broad field, look at:
http://en.wikipedia.org/wiki/Loop_transformation

>
>> If it is for performance: Writing native loops in C/C++ with some
>> optimization flags will give you best performance in most cases.
>>
>
> Best performance than Matlab, or best performance than
> "vectorized" C++?
>
best performance compared to vectorized code.
optimization flags of your compiler can force
loopoptimisation and other strategies.

>
>> The problem is that users who only know matlab and no other
>> programming languages are conditioned to believe that the
>> problem lies with for-loops as such, and not with matlab.
>>
>
> My question:
> When writing C++ code, do you thing I can have faster code
> if I use std::valarray<> in "the Matlab way", instead
> of using, say, std::vector<> and for-loops?
>
I do not know how optimized valarray<> is. You
should compare it using different matrix-/vector-sizes
and different optimization flags
of your compiler and post your results.

If you use GNU compilers, the flags are -O?
afaik -O0 up to -O3

And you should compare it to
     http://math-atlas.sourceforge.net/

which is supposed to gain very good performance.

> I must admit that this curiosity comes from my previous Matlab
> experiences, when I used to think to for-loops as being the devil,
> but from a naive point of view I can image that "vectorized"
> operations on std::valarray<> are optimized by smart compilation
> techniques... after all the programmer doesn't specify the
> order with which the operation as to be done, like in a foor-loop...
> Is this just fantasy?
>
In matlab for-loops are devil, because the interpreter
has to handle the loops, which slows things down.
If you make a navieve C implementation, you for-loops
are compiled to machinecode, which runs much faster
than the interpreted matlab for-loop.
vectorization gives matlab the ability to put the
operation into a optimized C routine, where the
essential and fast looping happens.

Greetings, Uwe

--
Dr. rer. nat. Uwe Schmitt
F&E Mathematik

mineway GmbH
Science Park 2
D-66123 Saarbr=FCcken

Telefon: +49 (0)681 8390 5334
Telefax: +49 (0)681 830 4376

uschmitt@mineway.de
www.mineway.de

Gesch=E4ftsf=FChrung: Dr.-Ing. Mathias Bauer
Amtsgericht Saarbr=FCcken HRB 12339


Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: Giovanni Gherdovich

Date: 07 Aug, 2008 16:48:11

Message: 21 of 24

Hello,

thank you for your answers.

Rune Allnor:
> Depending on exactly what you do, matlab *can* get very
> close to best-possible performance since it uses highly
> tuned low-level libraries. If your operation is covered by
> such a function, you might find it difficult to beat matlab.
> If not, don't be surprised if C++ code beats matlab by
> a factor 5-10 or more.

dave:
> (So, the answer to the OP's question is (as already noted): Don't worry
> about vectorizing, write loops and ask the compiler to optimize it, and
> you'll probably come close enough to Matlab's performance that you
> won't be able to tell the difference.)

Uwe:
> I mean: taking the inverse of a matrix is linear algebra,
> but multiplying two vectors component-wise is just... multiplying.
>
> > yes. but you can do some enrollment or other
> > access patterns for optimizing cache access.
> > this is a broad field, look at:
> > http://en.wikipedia.org/wiki/Loop_transformation

Rune Allnor:
> You would be surprised: There are for-loops at the core of all
> those libraries, even the BLAS libraries matlab is based on.
> There are smart compilation techniques involved, but to *optimize*
> the for-loops, not to *eliminate* them.

I was among the user who are "conditioned to believe that the
problem lies with for-loops as such, and not with matlab",
to use Rune's words.
Thank you all to point it out.

About the performance of numerical computation done using
std::valarray<>'s features:

Uwe:
> My question:
> When writing C++ code, do you thing I can have faster code
> if I use std::valarray<> in "the Matlab way", instead
> of using, say, std::vector<> and for-loops?
>
> > I do not know how optimized valarray<> is. You
> > should compare it using different matrix-/vector-sizes
> > and different optimization flags
> > of your compiler and post your results.

Rune Allnor:
> I don't know. I haven't used std::valarray<>. I know I have
> seen some comment somewhere that std::valarray<> was an early
> attempt at a standardized way to handle numbercrunching in C++,
> which was, well, not quite as successful as one might have
> whished for.

It seems that nobody knows if it's worth to use std::valarray<>
and related "vectorized" operators (provided by the standard
library) to do numerical computing in C++.

Googling this topic, I've found this interesting thread in
a forum of a site called "www.velocityreviews.com"
http://www.velocityreviews.com/forums/t277285-p-c-stl-valarrays-vs-vectors.html

One of the poster, who (like me) took the chapter "Vector Arithmetic"
on Stroustrup's book as The Truth, says that with valarray<>
you can do math at the speed of light, blah blah optimization
blah blah vectorization and so on.

Another user answers with what I find a more reasonable argument:
std::valarray<> was designed to meet the characteristic of vector
machines, like the Cray. If you don't have the Cray, there is
no point in doing math with valarray<> and related operators.

Anyway, as soon as I have some spare time I will check it on
my own, comparing the results with ATLAS as Uwe suggests.

Regards,
Giovanni Gherdovich

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to ?C++)?

From: Jerry Coffin

Date: 08 Aug, 2008 04:38:18

Message: 22 of 24

In article <a47fac46-bb33-4608-bd97-
f75cd419340f@d77g2000hsb.googlegroups.com>,
gherdovich@students.math.unifi.it says...

[ ... ]

> Another user answers with what I find a more reasonable argument:
> std::valarray<> was designed to meet the characteristic of vector
> machines, like the Cray. If you don't have the Cray, there is
> no point in doing math with valarray<> and related operators.

In theory that's right: the basic idea was to provide something that
could be implemented quite efficiently on vector machines. In fact, I've
never heard of anybody optimizing the code for a vector machine, so it
may be open to question whether it provides any real advantage on them.

OTOH, valarray _can_ make some code quite readable, so it's not always a
complete loss anyway.

--
    Later,
    Jerry.

The universe is a figment of its own imagination.

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab

From: Francis Glassborow

Date: 08 Aug, 2008 12:12:48

Message: 23 of 24

Jerry Coffin wrote:
> In article <a47fac46-bb33-4608-bd97-
> f75cd419340f@d77g2000hsb.googlegroups.com>,
> gherdovich@students.math.unifi.it says...
>
> [ ... ]
>
>> Another user answers with what I find a more reasonable argument:
>> std::valarray<> was designed to meet the characteristic of vector
>> machines, like the Cray. If you don't have the Cray, there is
>> no point in doing math with valarray<> and related operators.
>
> In theory that's right: the basic idea was to provide something that
> could be implemented quite efficiently on vector machines. In fact, I've
> never heard of anybody optimizing the code for a vector machine, so it
> may be open to question whether it provides any real advantage on them.

During the mid-90s both C and C++ were involved in adding features that
would support numerically intense programming. Unfortunately a couple of
years later the companies whose numerical experts doing the grunt work
withdrew support. By hindsight it might have been better to have shelved
the work but both WG14 and WG21 opted to continue hoping that they would
still produce something useful.

It is not obvious to those outside the numerical fields that actually
developing things like complex number support, support for array
arithmetic etc. is fraught with subtle traps.


>
> OTOH, valarray _can_ make some code quite readable, so it's not always a
> complete loss anyway.
>

--
Note that robinton.demon.co.uk addresses are no longer valid.

Subject: Re: vectorized computation in C++ such as those in Matlab (Matlab to

From: Giovanni Gherdovich

Date: 08 Aug, 2008 16:27:02

Message: 24 of 24

Hello,

> During the mid-90s both C and C++ were involved in adding features that
> would support numerically intense programming. Unfortunately a couple of
> years later the companies whose numerical experts doing the grunt work
> withdrew support.

Just for the sake of historical investigation, I found a thread on
this newsgroup from the far 1991, where Walter Bright (who might
be the same Walter Bright who designed the D programming language,
http://www.walterbright.com/
http://en.wikipedia.org/wiki/Walter_Bright , but I'm not sure)
lists some shortcomings for the C++ numerical programmer,
and item #6 is

"Optimization of array operations is inhibited by the 'aliasing'
problems."
http://en.wikipedia.org/wiki/Aliasing_(computing)

(retrieved from
http://groups.google.com/group/comp.lang.c++/browse_thread/thread/3df3ab6920fb71f5/feb0ec8ea7b24189?lnk=gst&q=numerical+analysis#feb0ec8ea7b24189

Then he mentions some solutions to this (two libraries, which
might be completely out of date nowaday).
Just to say that the Original Poster isn't the first to
address this issue...

> By hindsight it might have been better to have shelved
> the work but both WG14 and WG21 opted to continue hoping that they would
> still produce something useful.

Mmmh... I skimmed over the pages of Working Groups 14 and 21
http://www.open-std.org/jtc1/sc22/wg14
http://www.open-std.org/jtc1/sc22/wg21
and they don't seem to have vector arithmetic among their priorities.
Anyway, from what I've learned from this thread, the overall
theme can very well make no sense, because of CPUs characteristics.

Regards,
Giovanni Gh.

Tags for this Thread

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

rssFeed for this Thread

envelope graphic E-mail this page to a colleague

Public Submission Policy
NOTICE: Any content you submit to MATLAB Central, including personal information, is not subject to the protections which may be afforded information collected under other sections of The MathWorks, Inc. Web site. You are entirely responsible for all content that you upload, post, e-mail, transmit or otherwise make available via MATLAB Central. The MathWorks does not control the content posted by visitors to MATLAB Central and, does not guarantee the accuracy, integrity, or quality of such content. Under no circumstances will The MathWorks be liable in any way for any content not authored by The MathWorks, or any loss or damage of any kind incurred as a result of the use of any content posted, e-mailed, transmitted or otherwise made available via MATLAB Central. Read the complete Disclaimer prior to use.
Related Topics