Search code examples
pythonpackagesizelibrariesfilesize

How to print size of an imported library?


Is there anyway to print out the size of a library in python? I've tried this method, but it doesn't work:

>>> import sys
>>> import fastai as fastai
>>> import pytorch as torch

>>> print(sys.getsizeof(torch))
88
>>> print(sys.getsizeof(fastai))
88

I think fastai is around 1.9 MB and pytorch is around 320 MB, but I want to confirm.


Solution

  • try this

    import os, sys
    dir_size = lambda dirpath:sum([(sum([os.path.getsize(os.path.join(root, f)) for f in files]) + sum([dir_size(os.path.join(root, d)) for d in dirs])) for root, files, dirs in os.walk(dirpath)])
    def module_size(module_name):
        for p in sys.path:
            if os.path.exists(os.path.join(p, module_name)+'.py'):
                return f"{os.path.getsize(os.path.join(p, module_name)+'.py')/1024.0} KB"
            if os.path.exists(os.path.join(p, module_name)):            
                return f'{dir_size(os.path.join(p, module_name))/1024.0} KB'
        return 'Module not installed.'
    
    print(module_size('fastai'))
    print(module_size('pytorch'))