Home >Backend Development >Python Tutorial >How Can I Efficiently Measure the Memory Usage of a Python Process?

How Can I Efficiently Measure the Memory Usage of a Python Process?

Susan Sarandon
Susan SarandonOriginal
2024-12-02 18:54:15509browse

How Can I Efficiently Measure the Memory Usage of a Python Process?

Measuring Memory Consumption of Python Processes

Determining the total memory utilized by a Python process is crucial for optimizing resource allocation and discarding unnecessary cached data. Here's an effective solution that works across various operating systems:

Using the psutil Package

The psutil package offers a comprehensive set of tools for monitoring system resources, including memory usage. To measure the memory consumed by a Python process, follow these steps:

import psutil

# Create a Process object representing the current process
process = psutil.Process()

# Retrieve the memory information in bytes
memory_info = process.memory_info()

# Print the Resident Set Size (RSS) of the process
print(memory_info.rss)  # in bytes

Additional Notes:

  • Ensure that the psutil package is installed using pip install psutil.
  • For a quick estimate of process memory usage in MiB, use the following one-liner:
import os, psutil; print(psutil.Process(os.getpid()).memory_info().rss / 1024 ** 2)
  • In Python 2.7 and psutil version 5.6.3, the memory_info()[0] method was used instead of the rss attribute.

The above is the detailed content of How Can I Efficiently Measure the Memory Usage of a Python Process?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn