[Rod Stephens Books]
Index Books Python Examples About Rod Contact
[Mastodon] [Bluesky] [Facebook]
[Build Your Own Python Action Arcade!]

[Build Your Own Ray Tracer With Python]

[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

Title: Check memory usage in Python

[This system's memory is 92.8% used]

Yet another short, useful, but not very colorful example. (I promise this will be my last one of these for a while.)

This example looks at the computer's memory usage. Before we get to that, however, let's look at a little helper function that converts bytes into gigabytes.

bytes_to_gb

def bytes_to_gb(num_bytes): gb = num_bytes / (1024 ** 3) return gb

This function simply divides the number of bytes by 1024 to the 3rd power. You can modify it to convert to MB or KB if you need to by changing the power from 3 to 2 or 1 respectively.

Checking Memory Usage

The following code shows the example's main program.

import psutil memory = psutil.virtual_memory() total_gb = bytes_to_gb(memory.total) avail_gb = bytes_to_gb(memory.available) used_gb = bytes_to_gb(memory.used) print(f'Total: {total_gb:6.3f} GB') print(f'Avail: {avail_gb:6.3f} GB') print(f'Used: {used_gb:6.3f} GB') print(f'Usage: {memory.percent}%')

This code first calls psutil.virtual_memory to get memory usage information. It then uses the result's total, available, and used values. It calls bytes_to_gb to convert the values from bytes to gigabytes and prints the results.

Conclusion

My system's memory is usually more than 90% used, largely by browser tabs. Download the example to experiment with it and to see additional details.
© 2025 Rocky Mountain Computer Consulting, Inc. All rights reserved.