Book Image

Python High Performance Programming

By : Dr. Gabriele Lanaro
Book Image

Python High Performance Programming

By: Dr. Gabriele Lanaro

Overview of this book

<p>Python is a programming language with a vibrant community known for its simplicity, code readability, and expressiveness. The massive selection of third party libraries make it suitable for a wide range of applications. This also allows programmers to express concepts in fewer lines of code than would be possible in similar languages. The availability of high quality numerically-focused tools has made Python an excellent choice for high performance computing. The speed of applications comes down to how well the code is written. Poorly written code means poorly performing applications, which means unsatisfied customers.</p> <p>This book is an example-oriented guide to the techniques used to dramatically improve the performance of your Python programs. It will teach optimization techniques by using pure python tricks, high performance libraries, and the python-C integration. The book will also include a section on how to write and run parallel code.</p> <p>This book will teach you how to take any program and make it run much faster. You will learn state-of the art techniques by applying them to practical examples. This book will also guide you through different profiling tools which will help you identify performance issues in your program. You will learn how to speed up your numerical code using NumPy and Cython. The book will also introduce you to parallel programming so you can take advantage of modern multi-core processors.</p> <p>This is the perfect guide to help you achieve the best possible performance in your Python applications.</p>
Table of Contents (11 chapters)

Rewriting the particle simulator in NumPy


In this section, we will optimize our particle simulator by rewriting some parts of it in NumPy. From the profiling we did in Chapter 1, Benchmarking and Profiling, the slowest part of our program is the following loop contained in the ParticleSimulator.evolve method:

for i in range(nsteps):
  for p in self.particles:

    norm = (p.x**2 + p.y**2)**0.5
    v_x = (-p.y)/norm
    v_y = p.x/norm

    d_x = timestep * p.ang_speed * v_x
    d_y = timestep * p.ang_speed * v_y

    p.x += d_x
    p.y += d_y

We may notice that the body of the loop acts solely on the current particle. If we had an array containing the particle positions and angular speed, we could rewrite the loop using a broadcasted operation. In contrast, the loop over the time steps depends on the previous step and cannot be treated in a parallel fashion.

It's natural then, to store all the array coordinates in an array of shape (nparticles, 2) and the angular speed in an array of shape ...