03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

152 CHAPTER 5. META-PROGRAMMING<br />

• 3n assignments;<br />

• 5n reads;<br />

• 3n writes;<br />

• 2 memory allocations; and<br />

• 2 memory deallocations.<br />

As comparison, if we could write a single loop or an inline function:<br />

template <br />

void inline add3(const vector& x, const vector& y, const vector& z, vector& sum)<br />

{<br />

x.check size(size(y));<br />

x.check size(size(z));<br />

x.check size(size(sum));<br />

<strong>for</strong> (int i= 0; i < size(x); ++i)<br />

sum[i] = x[i] + y[i] + z[i];<br />

}<br />

This function per<strong>for</strong>ms:<br />

• 2n additions;<br />

• n assignments;<br />

• 3n reads;<br />

• n writes;<br />

The call of this function:<br />

add3(x, y, z, w);<br />

is of course less elegant than the operator notation. Often, one need another look at the<br />

documentation wether the first or the last argument contains the result. With operators this is<br />

evident.<br />

In high-per<strong>for</strong>mance software, programmers tend to implement a hard-coded version of every<br />

important operation instead of freely compose them from smaller expressions. The reason is<br />

obvious, our operator implementation per<strong>for</strong>med additionally:<br />

• 2n assignments;<br />

• 2n reads;<br />

• 2n writes;<br />

• 2 memory allocations; and<br />

• 2 memory deallocations.<br />

The good news is we have not per<strong>for</strong>med additional arithmetic. The bad news is that the<br />

operations above are more expensive. On modern computers, it takes much more time to<br />

read data from or write to the memory than executing fixed or floating point operations. 11<br />

Un<strong>for</strong>tunately, vectors in scientific applications tend to be rather long, often larger than the<br />

11 TODO: Maybe quantifying <strong>for</strong> some machine.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!