- Python High Performance(Second Edition)
- Gabriele Lanaro
- 346字
- 2021-07-09 21:01:54
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 the process.
Just like 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:
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:
From the Increment column, we can see that 100,000 Particle objects take 23.7 MiB of memory.
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 drawback--it prevents the addition of attributes other than the ones specified in __slots__ :
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:
By rewriting the Particle class using __slots__, we can save about 10 MiB of memory.
- LaTeX Cookbook
- Java 開發(fā)從入門到精通(第2版)
- DevOps for Networking
- Software Testing using Visual Studio 2012
- Java:Data Science Made Easy
- concrete5 Cookbook
- Python之光:Python編程入門與實(shí)戰(zhàn)
- jQuery Mobile移動(dòng)應(yīng)用開發(fā)實(shí)戰(zhàn)(第3版)
- 劍指大數(shù)據(jù):企業(yè)級(jí)數(shù)據(jù)倉(cāng)庫(kù)項(xiàng)目實(shí)戰(zhàn)(在線教育版)
- AutoCAD 2009實(shí)訓(xùn)指導(dǎo)
- Machine Learning With Go
- Apache Solr PHP Integration
- Python Automation Cookbook
- Three.js Essentials
- 川哥教你Spring Boot 2實(shí)戰(zhàn)