itsaboutcode
itsaboutcode

Reputation: 25099

How to find number of bytes taken by python variable

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?

Upvotes: 29

Views: 63703

Answers (9)

anantdd
anantdd

Reputation: 135

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

Upvotes: -1

ChristopheD
ChristopheD

Reputation: 116157

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))

Upvotes: 61

cem
cem

Reputation: 1655

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))

Upvotes: 0

HISI
HISI

Reputation: 4797

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

import sys
myint = 12
print(sys.getsizeof(myint))

Upvotes: 0

Jus
Jus

Reputation: 521

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.

Upvotes: 4

RICHA AGGARWAL
RICHA AGGARWAL

Reputation: 163

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

Upvotes: 2

ghostdog74
ghostdog74

Reputation: 342393

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.

Upvotes: 11

Cat Plus Plus
Cat Plus Plus

Reputation: 129764

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

Upvotes: 2

Alex Barrett
Alex Barrett

Reputation: 16455

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

Upvotes: 6

Related Questions