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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

5.3. EXPRESSION TEMPLATES 151<br />

}<br />

std::cout ≪ ”x = ” ≪ x ≪ std::endl;<br />

std::cout ≪ ”y = ” ≪ y ≪ std::endl;<br />

std::cout ≪ ”z = ” ≪ z ≪ std::endl;<br />

w= x + y + z;<br />

std::cout ≪ ”w= x + y + z = ” ≪ w ≪ std::endl;<br />

return 0;<br />

If this works properly, what is wrong with it? From the software engineering prospective:<br />

nothing. From the per<strong>for</strong>mance prospective: a lot.<br />

How is the statement executed:<br />

1. Create temporary variable sum <strong>for</strong> the addition of x and y;<br />

2. Per<strong>for</strong>m a loop reading x and y, adding it element-wise, and writing the result to sum;<br />

3. Copy sum to a temporary variable, say t xy, in the return statement;<br />

4. Delete sum;<br />

5. Create temporary variable sum <strong>for</strong> the addition of t xy and z;<br />

6. Per<strong>for</strong>m a loop reading t xy and z, adding it element-wise, and writing the result to sum;<br />

7. Copy sum to a temporary variable, say t xyz, in the return statement;<br />

8. Delete sum;<br />

9. Delete t xy;<br />

10. Per<strong>for</strong>m a loop reading t xyz and writing to w;<br />

11. Delete t xyz;<br />

This is admittedly the worst-case scenario. But it was the code that old compilers generated.<br />

Modern compilers per<strong>for</strong>m more optimizations by static code analysis and can avoid copying<br />

the return value into the temporaries t xy and t xyz. Instead of creating the temporaries t xy<br />

and t xyz, they become aliases <strong>for</strong> the respective sum temporaries.<br />

The optimized version per<strong>for</strong>ms:<br />

1. Create temporary variable sum (<strong>for</strong> distinction sum xy) <strong>for</strong> the addition of x and y;<br />

2. Per<strong>for</strong>m a loop reading x and y, adding it element-wise, and writing the result to sum;<br />

3. Create temporary variable sum (<strong>for</strong> distinction sum xyz) <strong>for</strong> the addition of sum xy and z;<br />

4. Per<strong>for</strong>m a loop reading sum xy and z, adding it, and writing the result to sum xyz;<br />

5. Delete sum xy;<br />

6. Per<strong>for</strong>m a loop reading sum xyz and writing to w;<br />

7. Delete sum xyz;<br />

How much operations did we per<strong>for</strong>m? Say our vectors have lenght n then we have in total:<br />

• 2n additions;

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

Saved successfully!

Ooh no, something went wrong!