Python узнать размер переменной

Функция sizeof в Python: управление использованием памяти

Когда мы пишем большие скрипты или многострочный код, управление памятью должно быть нашим главным приоритетом. Следовательно, мы должны иметь представление об эффективном обращении с памятью в дополнение к хорошему знанию программирования.

У нас есть много функций, данных в Python, чтобы получить размер в памяти конкретного объекта, присутствующего в программе, и одна из таких функций – __sizeof __(). В этом руководстве мы узнаем о функции __sizeof __() в и ее работе в программе Python.

Что такое функция sizeof() в Python?

Функция __sizeof __() в Python точно не сообщает нам размер объекта. Она не возвращает размер объекта-генератора, поскольку Python не может заранее сообщить нам размер генератора. Тем не менее, на самом деле она возвращает внутренний размер для определенного объекта (в байтах), занимающего память.

Чтобы понять это, давайте посмотрим на следующий пример программы с бесконечным объектом-генератором.

# A default function with endless generator object in it def endlessGenerator(): # A counting variable to initialize the generator counting = 0 # Using while loop to create an endless generator while True: yield counting counting += 1 # Creating infinite loop # Printing memory size of a generator object print("Internal memory size of endless generator object: ", endlessGenerator.__sizeof__())
Internal memory size of endless generator object: 120

Мы использовали функцию по умолчанию, то есть endlessGenerator(), для создания бесконечного объекта-генератора в программе. В функции мы инициализировали переменную, то есть counting = 0. Мы использовали цикл while для счетной переменной, не задавая точку останова в цикле.

Создав бесконечный цикл в функции, мы сделали функцию по умолчанию бесконечным объектом-генератором. Наконец, мы напечатали размер внутренней памяти бесконечного объекта-генератора с помощью функции __sizeof __().

Теперь мы можем четко понять работу функции __sizeof __(). Поскольку объект бесконечного генератора в приведенной выше программе не имеет конца или точки останова, Python не может заранее сообщить нам размер генератора. Но в то же время мы можем проверить размер внутренней памяти, выделенной объекту-генератору функцией __sizeof __(), поскольку он должен занимать некоторую внутреннюю память в Python.

Давайте рассмотрим еще один пример, в котором мы используем функцию __sizeof __(), чтобы получить размер внутренней памяти без каких-либо накладных расходов.

# Define an empty list in the program emptyList = [] # Printing size of empty list print("Internal memory size of an empty list: ", emptyList.__sizeof__()) # Define some lists with elements a = [24] b = [24, 26, 31, 6] c = [1, 2, 6, 5, 415, 9, 23, 29] d = [4, 5, 12, 3, 2, 9, 20, 40, 32, 64] # Printing internal memory size of lists print("Memory size of first list: ", a.__sizeof__()) print("Memory size of second list: ", b.__sizeof__()) print("Memory size of third list: ", c.__sizeof__()) print("Memory size of fourth list: ", d.__sizeof__())
Internal memory size of an empty list: 40 Memory size of first list: 48 Memory size of second list: 104 Memory size of third list: 104 Memory size of fourth list: 136

Используя функцию __sizeof __(), мы можем ясно видеть, что размер внутренней памяти пустого списка составляет 40 байтов, и каждый элемент, присутствующий в списке, добавляет размер 8 байтов к общему размеру памяти списка.

Источник

Читайте также:  Javascript свойства объекта dom

Определите размер объекта в Python

Определите размер объекта в Python

  1. модуль sys в Python
  2. Используйте функцию getsizeof() в модуле sys , чтобы получить размер объекта в Python

В программировании существуют различные встроенные типы данных, такие как числовые, текстовые, последовательные и логические. В Python все эти типы данных считаются объектами. Каждому объекту требуется место в памяти для хранения самого себя. Итак, эти объекты хранятся в памяти и занимают место в виде bytes . Каждый объект имеет разный размер хранилища, и в этом руководстве показано, как определить размер объекта в Python.

модуль sys в Python

Модуль sys Python помогает пользователю выполнять различные операции и манипуляции с различными частями среды выполнения Python, предоставляя несколько функций и переменных. С интерпретатором можно легко взаимодействовать через различные переменные и функции. Используя модуль sys , вы можете легко получить доступ к системным функциям и параметрам.

Модуль sys также используется для определения размера объекта в Python.

Используйте функцию getsizeof() в модуле sys , чтобы получить размер объекта в Python

Функция getsizeof() , предоставляемая модулем sys , является наиболее часто используемой функцией для получения размера конкретного объекта в Python. Эта функция сохраняет объект в качестве аргумента функции, вызывает функцию этого объекта sizeof() и, наконец, возвращает результат.

import sys  s=sys.getsizeof('size of this string object') print(s)  s=sys.getsizeof(1010101) print(s)  s=sys.getsizeof(1:'size',2:'of',3:'this',4:'dictionary'>) print(s) 

Обратите внимание, что размеры возвращаемых объектов указаны в байтах.

Lakshay Kapoor is a final year B.Tech Computer Science student at Amity University Noida. He is familiar with programming languages and their real-world applications (Python/R/C++). Deeply interested in the area of Data Sciences and Machine Learning.

Читайте также:  Сумка dior из питона

Сопутствующая статья — Python Object

Источник

How to Get the Size of a Python Object (Examples & Theory)

To get the size of a Python object, you can use the getsizeof() function from the sys module. This function returns the size of an object in bytes.

For example, let’s print the size of a list and the size of an integer:

import sys l = [1, 2, 3, 4, 5] # Get the size of the object in bytes object_size = sys.getsizeof(l) print(object_size) print(12)

⚠️ Keep in mind that sys.getsizeof() function only returns the size of the object itself. It does NOT take into account the size of inner objects. For instance, measuring the size of a list of lists with getsizeof() method will only return the size of the outer list and not take into account the sizes of the inner lists.

The Big Issue with sys.getsizeof() Function

To illustrate the problem that arises when measuring object sizes with sys.getsizeof() function:

  • Let’s measure the size of a list of numbers.
  • Let’s compare the size to a list that consists of 5 lists of numbers.
import sys nums = [1, 2, 3, 4, 5] print(sys.getsizeof(nums)) more_nums = [ [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5] ] print(sys.getsizeof(more_nums))

By looking at the above, you would expect more_nums to be bigger in size than nums . This is because more_nums is a list that has 5 similar lists to the nums list.

But here’s what the output says:

What?! The sizes of the lists are the same even though they’re clearly different sizes.

As a matter of fact, the list length will always be the same as long as the number of objects is the same.

For example, let’s measure the size of a list of 5 characters:

import sys nums = ['t', 'e', 's', 't', 's'] print(sys.getsizeof(nums))

The sys.getsizeof() function only works when measuring the size of a built-in object. But if you’re interested in the true size of the object among its contents objects, you need to pick a different approach.

How to Measure the True Size of a Python Object?

Because of the limitations in sys.getsizeof() function, you won’t be able to determine the size of a nested object in Python. For example, you won’t be able to measure the size of a list of lists or a list of strings reliably.

Читайте также:  Python generate unique ids

A better way to calculate the size of a Python object is to use a recursive function that iterates the objects of the objects to check their size to accumulate the total size of the object.

To keep it in scope, we’re not going to write such a recursive function.

Instead, you can use an existing solution called Pympler, which is a free Python package you can install with pip.

With pympler installed, you can start estimating the size of your Python objects by using the pympler.asizeof.asizeof() function.

from pympler import asizeof nums = [1, 2, 3, 4, 5] print(asizeof.asizeof(nums)) more_nums = [ [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5] ] print(asizeof.asizeof(more_nums))

Looks better! The asizeof() function not only calculates the space an object takes but also combines it with what the nested elements eat up. Now the list of lists is bigger than a single list of numbers which makes sense.

And if you expected the list of lists to take 5 x more space than the list, you were wrong.

Intuitively, that would be the case. But behind the scenes, a “lot of” memory is spent building the list, the list inside a list before adding a single integer. This initial cost of building the objects might change the size expectations of the objects you’re measuring.

For example, to build an empty list with an empty list inside, you already need 120 bytes of memory.

from pympler import asizeof print(asizeof.asizeof([[]])) # Output: 120

Then the rest of the memory consumption is based on what values you add to the inner lists and how many inner lists you’ll have.

Summary

Today you learned how to measure the size of a Python object.

To take home, the out-of-box method sys.getsizeof() is limited and doesn’t care what’s inside the objects. In other words, most of the time it doesn’t return the size you want.

A better and more intuitive way to measure the true size of an object is by measuring the inner object’s size too. You can do this with the Pympler package asizeof class’s asizeof() function.

Источник

Оцените статью