Book Image

C++ High Performance

By : Björn Andrist, Viktor Sehr
5 (1)
Book Image

C++ High Performance

5 (1)
By: Björn Andrist, Viktor Sehr

Overview of this book

C++ is a highly portable language and can be used to write both large-scale applications and performance-critical code. It has evolved over the last few years to become a modern and expressive language. This book will guide you through optimizing the performance of your C++ apps by allowing them to run faster and consume fewer resources on the device they're running on without compromising the readability of your code base. The book begins by helping you measure and identify bottlenecks in a C++ code base. It then moves on by teaching you how to use modern C++ constructs and techniques. You'll see how this affects the way you write code. Next, you'll see the importance of data structure optimization and memory management, and how it can be used efficiently with respect to CPU caches. After that, you'll see how STL algorithm and composable Range V3 should be used to both achieve faster execution and more readable code, followed by how to use STL containers and how to write your own specialized iterators. Moving on, you’ll get hands-on experience in making use of modern C++ metaprogramming and reflection to reduce boilerplate code as well as in working with proxy objects to perform optimizations under the hood. After that, you’ll learn concurrent programming and understand lock-free data structures. The book ends with an overview of parallel algorithms using STL execution policies, Boost Compute, and OpenCL to utilize both the CPU and the GPU.
Table of Contents (13 chapters)

Postponing an sqrt computation when comparing distances

In this example, we will show you how to use a proxy object in order to postpone, or even avoid, using the computationally heavy std::sqrt() method when comparing the distance between two dimensional points.

A simple two-dimensional point class

Let's start with a simple point class in 2D. It has x and y coordinates and a member function, which calculates the distance to another point:

class Point{
Point(float x, float y) : x_{x}, y_{y} {}
auto distance(const Point& p) const {
auto dist_sqrd = std::pow(x_-p.x_, 2) + std::pow(y_-p.y_, 2)
return std::sqrt(dist_sqrd);
float x_{};
float y_{};

A simple usage example would be as follows...