Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Efficiently Measure Python Object Memory Usage with sys.getsizeof()

Efficiently Measure Python Object Memory Usage with sys.getsizeof()

With sys.getsizeof() you can check the memory usage of an object:

import sys

mylist = range(0, 10000)
print(sys.getsizeof(mylist))
# 48

Woah… wait… why is this huge list only 48 bytes?

It’s because the range function returns an iterable object that only behaves like a list of numbers, but internally simply keeps count of the last iteration number. A range is a lot more memory efficient than using an actual list of numbers.

You can see for yourself by using a list comprehension to create an actual Python list of numbers from the same range:

import sys

myreallist = [x for x in range(0, 10000)]
print(sys.getsizeof(myreallist))
# 87632

That’s roughly 87KB for 10,000 numbers.


Python

  1. Mastering Python For Loops: Syntax, Examples, and Advanced Patterns
  2. Mastering Python Objects & Classes: A Practical Guide
  3. Hello World: Building Your First Python Application
  4. Mastering Python's range() Function: From Basics to Advanced Use Cases
  5. Python time.sleep(): How to Add Delays in Your Code (Example)
  6. Checking File and Directory Existence in Python – A Practical Guide
  7. Master Python Debugging: Efficient Techniques & Best Practices
  8. Enforce a Minimum Python Version in Your Script
  9. Quarterly Supply Chain Health Check: Ensure Smooth Operations
  10. Prepare Your Excavator for Spring: A Comprehensive Guide