473,769 Members | 6,203 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

vectorized computation in C++ such as those in Matlab (Matlab toC++)?

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);
Jul 22 '08
14 3146
In article <6d************ *************** *******@x41g200 0hsb.googlegrou ps.com>,
Rune Allnor <al****@tele.nt nu.nowrote:
>On 6 Aug, 14:54, Giovanni Gherdovich
<gherdov...@st udents.math.uni fi.itwrote:
>I'm aware of Matlab "vectorizat ion" 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
Aug 6 '08 #11
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 "conditione d 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<i n "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<w as 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.velocityre views.com"
http://www.velocityreviews.com/forum...s-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<w as 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
Aug 7 '08 #12
In article <a47fac46-bb33-4608-bd97-
f7**********@d7 7g2000hsb.googl egroups.com>,
gh********@stud ents.math.unifi .it says...

[ ... ]
Another user answers with what I find a more reasonable argument:
std::valarray<w as 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.
Aug 8 '08 #13
Jerry Coffin wrote:
In article <a47fac46-bb33-4608-bd97-
f7**********@d7 7g2000hsb.googl egroups.com>,
gh********@stud ents.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.
Aug 8 '08 #14
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

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

(retrieved from
http://groups.google.com/group/comp....b0ec8ea7b24189

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.
Aug 8 '08 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
16929
by: Mathias | last post by:
Dear NG, I currently ty to switch from matlab to python/scipy but have a lot of trouble with images. What I need is a function for subsequently displaying a number of 2D-matrices as an image. I tried: - Image.show() which is nice but slow and I don't seem to be able to either close the window nor draw again to the same window, so I end up with 100 pictures on the screen... - scipy.xplt.imagesc() and scipy.plt.imagesc() crash
4
2762
by: dataangel | last post by:
I'm a student who's considering doing a project for a Machine Learning class on pathing (bots learning to run through a maze). The language primarily used by the class has been Matlab. I would prefer to do the bulk of the project in python because I'm familiar with pygame (for the visuals) but I already have a lot of AI code written in Matlab. I'd like to be able to call Matlab code from within python. I'm not sure this is possible. My...
3
4005
by: Mohammed Smadi | last post by:
Hi; Does anyone know if we can call matlab for a python or bash script while feeding the matlab script some command line arguments? I have an interactive matlab script which i want to automate by feeding the args from a script. I know this is probably more suitable to a matlab group but any ideas will be appreciated.
6
22260
by: Lars Christiansen | last post by:
Hi! I am a master student in (geo)physics at the University of Copenhagen and part of a study group on C++ as a scientific programming language. I, and the other students in the group, have previously used MatLab in different courses to solve problems, and find it very easy to use. This has led us to the discussion: When should we use C++ instead of MatLab? When is C++ superior to MatLab - and when is it the other way
53
4382
by: Michael Tobis | last post by:
Someone asked me to write a brief essay regarding the value-add proposition for Python in the Fortran community. Slightly modified to remove a few climatology-related specifics, here it is. I would welcome comments and corrections, and would be happy to contribute some version of this to the Python website if it is of interest. ===
2
6853
by: Quina | last post by:
Hi there, i'm building an windows application to manage my disc collection. I also want to enable it with cd recognition features on audio CDs. In order to do this I must submit the CD info (discID, ...) to freedb.org. The problem is that I don't know how to retrieve the Table Of Contents (toc) from the disc. The information provided by freedb tells how to calculate the DiscID, based on the toc, but it doesn't explain how to get the...
9
5297
by: Carl | last post by:
I am desperately looking for a way to call Python from Matlab. I have become used to Python's rich syntax and large number of libraries, and feel ridiculously clumsy being stuck with Matlab's rather restricted facilities for doing other things than standard mathematical work. Does anyone know of good techniques (or readily available software) for achieving a cross-language support between Python and Matlab? Carl
10
5261
by: Chao | last post by:
I've been trying to develop some numerical codes with python, however got disappointed. A very simple test, a = 1.0 for i in range(1000): for j in range(1000): a = a+1
4
13752
by: itcecsa | last post by:
Hi, I am implementing a small Python project, what I am going to do is to open Matlab and run some M-files, and get some output from Matlab command prompt. I have no idea how to open Matlab from Python! Any suggestions would be appriciated!
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10211
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10045
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9994
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7409
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6673
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5299
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.