Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Advanced Python Programming

You're reading from   Advanced Python Programming Accelerate your Python programs using proven techniques and design patterns

Arrow left icon
Product type Paperback
Published in Mar 2022
Publisher Packt
ISBN-13 9781801814010
Length 606 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Quan Nguyen Quan Nguyen
Author Profile Icon Quan Nguyen
Quan Nguyen
Arrow right icon
View More author details
Toc

Table of Contents (32) Chapters Close

Preface 1. Section 1: Python-Native and Specialized Optimization
2. Chapter 1: Benchmarking and Profiling FREE CHAPTER 3. Chapter 2: Pure Python Optimizations 4. Chapter 3: Fast Array Operations with NumPy, Pandas, and Xarray 5. Chapter 4: C Performance with Cython 6. Chapter 5: Exploring Compilers 7. Chapter 6: Automatic Differentiation and Accelerated Linear Algebra for Machine Learning 8. Section 2: Concurrency and Parallelism
9. Chapter 7: Implementing Concurrency 10. Chapter 8: Parallel Processing 11. Chapter 9: Concurrent Web Requests 12. Chapter 10: Concurrent Image Processing 13. Chapter 11: Building Communication Channels with asyncio 14. Chapter 12: Deadlocks 15. Chapter 13: Starvation 16. Chapter 14: Race Conditions 17. Chapter 15: The Global Interpreter Lock 18. Section 3: Design Patterns in Python
19. Chapter 16: The Factory Pattern 20. Chapter 17: The Builder Pattern 21. Chapter 18: Other Creational Patterns 22. Chapter 19: The Adapter Pattern 23. Chapter 20: The Decorator Pattern 24. Chapter 21: The Bridge Pattern 25. Chapter 22: The Façade Pattern 26. Chapter 23: Other Structural Patterns 27. Chapter 24: The Chain of Responsibility Pattern 28. Chapter 25: The Command Pattern 29. Chapter 26: The Observer Pattern 30. Assessments 31. Other Books You May Enjoy

Optimizing our code

Now that we have identified where exactly our application is spending most of its time, we can make some changes and assess the resulting improvement in performance.

There are different ways to tune up our pure Python code. The way that typically produces the most significant results is to improve the algorithms used. In this case, instead of calculating the velocity and adding small steps, it will be more efficient (and correct, as it is not an approximation) to express the equations of motion in terms of radius, r, and angle, alpha, (instead of x and y), and then calculate the points on a circle using the following equation:

    x = r * cos(alpha) 
    y = r * sin(alpha)

Another optimization method lies in minimizing the number of instructions. For example, we can precalculate the timestep * p.ang_vel factor that doesn't change with time. We can exchange the loop order (first, we iterate on particles, then we iterate on time steps) and put the calculation of the factor outside the loop on the particles.

The line-by-line profiling also showed that even simple assignment operations can take a considerable amount of time. For example, the following statement takes more than 10 percent of the total time:

    v_x = (-p.y)/norm

We can improve the performance of the loop by reducing the number of assignment operations performed. To do that, we can avoid intermediate variables by rewriting the expression into a single, slightly more complex statement (note that the right-hand side gets evaluated completely before being assigned to the variables), as follows:

    p.x, p.y = p.x - t_x_ang*p.y/norm, p.y + t_x_ang * 
    p.x/norm

This leads to the following code:

        def evolve_fast(self, dt): 
            timestep = 0.00001 
            nsteps = int(dt/timestep) 
            # Loop order is changed 
            for p in self.particles: 
                t_x_ang = timestep * p.ang_vel 
                for i in range(nsteps): 
                    norm = (p.x**2 + p.y**2)**0.5 
                    p.x, p.y = (p.x - t_x_ang * p.y/norm,
                        p.y + t_x_ang * p.x/norm)

After applying the changes, we should verify that the result is still the same by running our test. We can then compare the execution times using our benchmark, as follows:

$ time python simul.py # Performance Tuned
real    0m0.756s
user    0m0.714s
sys    0m0.036s
$ time python simul.py # Original
real    0m0.863s
user    0m0.831s
sys    0m0.028s

As you can see, we obtained only a modest increment in speed by making a pure Python micro-optimization.

You have been reading a chapter from
Advanced Python Programming - Second Edition
Published in: Mar 2022
Publisher: Packt
ISBN-13: 9781801814010
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image