How do I determine the size of an object in Python?

前端 未结 13 1481
半阙折子戏
半阙折子戏 2020-11-21 21:53

I want to know how to get size of objects like a string, integer, etc. in Python.

Related question: How many bytes per element are there in a Python list (tuple)?

13条回答
  •  一整个雨季
    2020-11-21 22:46

    I use this trick... May won't be accurate on small objects, but I think it's much more accurate for a complex object (like pygame surface) rather than sys.getsizeof()

    import pygame as pg
    import os
    import psutil
    import time
    
    
    process = psutil.Process(os.getpid())
    pg.init()    
    vocab = ['hello', 'me', 'you', 'she', 'he', 'they', 'we',
             'should', 'why?', 'necessarily', 'do', 'that']
    
    font = pg.font.SysFont("monospace", 100, True)
    
    dct = {}
    
    newMem = process.memory_info().rss  # don't mind this line
    Str = f'store ' + f'Nothing \tsurface use about '.expandtabs(15) + \
          f'0\t bytes'.expandtabs(9)  # don't mind this assignment too
    
    usedMem = process.memory_info().rss
    
    for word in vocab:
        dct[word] = font.render(word, True, pg.Color("#000000"))
    
        time.sleep(0.1)  # wait a moment
    
        # get total used memory of this script:
        newMem = process.memory_info().rss
        Str = f'store ' + f'{word}\tsurface use about '.expandtabs(15) + \
              f'{newMem - usedMem}\t bytes'.expandtabs(9)
    
        print(Str)
        usedMem = newMem
    

    On my windows 10, python 3.7.3, the output is:

    store hello          surface use about 225280    bytes
    store me             surface use about 61440     bytes
    store you            surface use about 94208     bytes
    store she            surface use about 81920     bytes
    store he             surface use about 53248     bytes
    store they           surface use about 114688    bytes
    store we             surface use about 57344     bytes
    store should         surface use about 172032    bytes
    store why?           surface use about 110592    bytes
    store necessarily    surface use about 311296    bytes
    store do             surface use about 57344     bytes
    store that           surface use about 110592    bytes
    

提交回复
热议问题