How to find number of bytes taken by python variable

Question:

Is there anyway i can know how much bytes taken by particular variable in python. E.g; lets say i have

int = 12
print (type(int))

it will print

<class 'int'> 

But i wanted to know how many bytes it has taken on memory? is it possible?

Asked By: itsaboutcode

||

Answers:

You can find the functionality you are looking for here (in sys.getsizeof – Python 2.6 and up).

Also: don’t shadow the int builtin!

import sys
myint = 12
print(sys.getsizeof(myint))
Answered By: ChristopheD

In Python >= 2.6 you can use sys.getsizeof.

Answered By: Alex Barrett

You could also take a look at Pympler, especially its asizeof module, which unlike sys.getsizeof works with Python >=2.2.

Answered By: Cat Plus Plus

if you want to know size of int, you can use struct

>>> import struct
>>> struct.calcsize("i")
4

otherwise, as others already pointed out, use getsizeof (2.6). there is also a recipe you can try.

Answered By: ghostdog74

on python command prompt, you can use size of function

   $ import python 
    $ import ctypes
    $ ctypes.sizeof(ctypes.c_int)

and read more on it from https://docs.python.org/2/library/ctypes.html

Answered By: RICHA AGGARWAL

Numpy offers infrastructure to control data size. Here are examples (py3):

import numpy as np
x = np.float32(0)
print(x.nbytes) # 4
a = np.zeros((15, 15), np.int64)
print(a.nbytes) # 15 * 15 * 8 = 1800

This is super helpful when trying to submit data to the graphics card with pyopengl, for example.

Answered By: Jus

In Python 3 you can use sys.getsizeof().

import sys
myint = 12
print(sys.getsizeof(myint))
Answered By: HISI

The best library for that is guppy:

import guppy
import inspect 

def get_object_size(obj):
    h = guppy.hpy()
    callers_local_vars = inspect.currentframe().f_back.f_locals.items()

    vname = "Constant"

    for var_name, var_val in callers_local_vars:
        if var_val == obj:
            vname = str(var_name)

    size = str("{0:.2f} GB".format(float(h.iso(obj).domisize) / (1024 * 1024)))

   return str("{}: {}".format(vname, size))
Answered By: cem

The accepted answer sys.getsizeof is correct.

But looking at your comment about the accepted answer you might want the number of bits a number is occupying in binary. You can use bit_length

(16).bit_length() # '10000' in binary
>> 5

(4).bit_length() # '100' in binary
>> 3
Answered By: anantdd
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.