How to Eat Memory using Python?

前端 未结 5 516
无人及你
无人及你 2021-01-31 16:10

Just for experiment, and Fun... I am trying to create an app that can \"Purposely\" consume RAM as much as we specify immediately. e.g. I want to consume 512 MB RAM, then the ap

5条回答
  •  无人及你
    2021-01-31 16:55

    You won't be able to allocate all the memory you can using constructs like

    s = ' ' * BIG_NUMBER
    

    It is better to append a list as in

    a = []
    while True:
        print len(a)
        a.append(' ' * 10**6)
    

    Here is a longer code which gives more insight on the memory allocation limits:

    import os
    import psutil
    
    PROCESS = psutil.Process(os.getpid())
    MEGA = 10 ** 6
    MEGA_STR = ' ' * MEGA
    
    def pmem():
        tot, avail, percent, used, free = psutil.virtual_memory()
        tot, avail, used, free = tot / MEGA, avail / MEGA, used / MEGA, free / MEGA
        proc = PROCESS.get_memory_info()[1] / MEGA
        print('process = %s total = %s avail = %s used = %s free = %s percent = %s'
              % (proc, tot, avail, used, free, percent))
    
    def alloc_max_array():
        i = 0
        ar = []
        while True:
            try:
                #ar.append(MEGA_STR)  # no copy if reusing the same string!
                ar.append(MEGA_STR + str(i))
            except MemoryError:
                break
            i += 1
        max_i = i - 1
        print 'maximum array allocation:', max_i
        pmem()
    
    def alloc_max_str():
        i = 0
        while True:
            try:
                a = ' ' * (i * 10 * MEGA)
                del a
            except MemoryError:
                break
            i += 1
        max_i = i - 1
        _ = ' ' * (max_i * 10 * MEGA)
        print 'maximum string allocation', max_i
        pmem()
    
    pmem()
    alloc_max_str()
    alloc_max_array()
    

    This is the output I get:

    process = 4 total = 3179 avail = 2051 used = 1127 free = 2051 percent = 35.5
    maximum string allocation 102
    process = 1025 total = 3179 avail = 1028 used = 2150 free = 1028 percent = 67.7
    maximum array allocation: 2004
    process = 2018 total = 3179 avail = 34 used = 3144 free = 34 percent = 98.9
    

提交回复
热议问题