Search icon CANCEL
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

Profiling memory usage with memory_profiler

In some cases, high memory usage constitutes an issue. For example, if we want to handle a huge number of particles, we will incur a memory overhead due to the creation of many Particle instances.

The memory_profiler module summarizes, in a way similar to line_profiler, the memory usage of a process.

The memory_profiler package is also available on PyPI. You should also install the psutil module (https://github.com/giampaolo/psutil) as an optional dependency that will make memory_profiler considerably faster.

Just as with line_profiler, memory_profiler also requires the instrumentation of the source code by placing a @profile decorator on the function we intend to monitor. In our case, we want to analyze the benchmark function.

We can slightly change benchmark to instantiate a considerable amount (100000) of Particle instances and decrease the simulation time, as follows:

    def benchmark_memory(): 
        particles = [
                     Particle(uniform(-1.0, 1.0), 
                              uniform(-1.0, 1.0), 
                              uniform(-1.0, 1.0)) 
                      for i in range(100000)
            ] 
        simulator = ParticleSimulator(particles) 
        simulator.evolve(0.001)

We can use memory_profiler from an IPython shell through the %mprun magic command, as shown in the following screenshot:

Figure 1.8 – Output from memory_profiler

Figure 1.8 – Output from memory_profiler

It is possible to run memory_profiler from the shell using the mprof run command after adding the @profile decorator.

From the Increment column, we can see that 100,000 Particle objects take 23.7 MiB of memory.

1 mebibyte (MiB) is equivalent to 1,048,576 bytes. It is different from 1 megabyte (MB), which is equivalent to 1,000,000 bytes.

We can use __slots__ on the Particle class to reduce its memory footprint. This feature saves some memory by avoiding storing the variables of the instance in an internal dictionary. This strategy, however, has a small limitation—it prevents the addition of attributes other than the ones specified in __slots__. You can see this feature in use in the following code snippet:

    class Particle:
        __slots__ = ('x', 'y', 'ang_vel') 
        def __init__(self, x, y, ang_vel): 
            self.x = x 
            self.y = y 
            self.ang_vel = ang_vel

We can now rerun our benchmark to assess the change in memory consumption. The result is displayed in the following screenshot:

Figure 1.9 – Improvement in memory consumption

Figure 1.9 – Improvement in memory consumption

By rewriting the Particle class using __slots__, we can save about 10 MiB of memory.

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