使用Python占用内存

56 投票
6 回答
41766 浏览
提问于 2025-04-16 19:22

我正在尝试创建一个应用程序,可以“故意”按照我们指定的数量立即消耗内存。例如,我想消耗512 MB的内存,那么这个应用就会直接消耗512 MB。

我在网上搜索过,大多数方法都是使用循环来填充内存,填充一些变量或数据。但我觉得这种方式填充内存太慢,而且可能不够准确。

我在寻找一个关于内存管理的Python库,发现了这个 http://docs.python.org/library/mmap.html。但是我不知道怎么用这个库一次性占用内存。

我曾经见过一个内存占用应用,但不知道它们是怎么写的……

所以,有没有其他更好的建议,可以立即用随机数据填充内存?还是说我应该用循环手动填充数据,但用多线程来加快速度呢?

6 个回答

12
x = bytearray(1024*1024*1000)

大约占用1GB的内存

14

你不能像使用下面的方式那样,分配所有你能用的内存:

s = ' ' * BIG_NUMBER

更好的做法是像下面这样添加一个列表:

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

这里有一段更长的代码,可以让你更深入了解内存分配的限制:

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

这是我得到的输出:

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
71

一种简单的方法可能是:

some_str = ' ' * 512000000

在我的测试中,这个方法效果不错。

补充说明:在Python 3中,你可能想用 bytearray(512000000) 来代替。

撰写回答