如何使用Python吃内存?

Yeo*_*Yeo 29 python memory memory-management

只是为了实验,有趣......我正在尝试创建一个可以"有目的"消耗RAM的应用程序,就像我们立即指定的那样.例如,我想消耗512 MB RAM,然后该应用程序将直接消耗512 MB.

我在网上搜索,大多数都在使用while循环来填充ram的变量或数据.但我认为这是填充RAM的缓慢方式,也可能不准确.

我在python中寻找一个关于内存管理的库.并且遇到了这些http://docs.python.org/library/mmap.html.但无法弄清楚如何使用这些库一次性吃掉RAM空间.

我曾见过mem-eater应用程序,但不知道它们是如何编写的......

那么,还有其他更好的建议立即用随机数据填充RAM吗?或者我应该只使用while循环来手动填充数据,但使用多线程来加快速度?

Jas*_*ijn 42

一种简单的方法可能是:

some_str = ' ' * 512000000
Run Code Online (Sandbox Code Playgroud)

似乎在我的测试中工作得很好.

编辑:在Python 3中,您可能想要使用bytearray(512000000).

  • @YeoEoeY:Python无法分配比操作系统允许的内存更多的内存. (3认同)
  • 决定一个块大小(例如,1024)而不是请求一个巨大的字符串,请求许多小字符串. (2认同)

小智 12

x = bytearray(1024*1024*1000)
Run Code Online (Sandbox Code Playgroud)

占用约 1GB 内存


mar*_*opa 8

您将无法使用类似的结构分配所有内存

s = ' ' * BIG_NUMBER
Run Code Online (Sandbox Code Playgroud)

最好是附加一个列表

a = []
while True:
    print len(a)
    a.append(' ' * 10**6)
Run Code Online (Sandbox Code Playgroud)

这是一个更长的代码,可以更深入地了解内存分配限制:

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()
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出:

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
Run Code Online (Sandbox Code Playgroud)

  • 我不得不将一行更改为“tot、avail、percentage、used、free、active、inactive、buffers、cached = psutil.virtual_memory()”以避免“ValueError: too many values to unpack”。 (3认同)