使用 Python 吃掉内存

新手上路,请多包涵

我正在尝试创建一个可以“故意”消耗我们立即指定的 RAM 的应用程序。例如,我想消耗 512 MB RAM,那么应用程序将直接消耗 512 MB。

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

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

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

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

原文由 Yeo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 658
2 个回答

一种简单的方法可能是:

 some_str = ' ' * 512000000

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

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

原文由 Jasmijn 发布,翻译遵循 CC BY-SA 3.0 许可协议

您将无法使用像这样的构造分配所有内存

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

原文由 markolopa 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题