memtest.py 脚本用于支持 9.8 节的一个演示——示例 9-12。

memtest.py 脚本从命令行中接收一个模块的名称,加载那个模块。假设模块中定义有一个名为 Vector 的类,memtest.py 脚本会创建一个由一千万个实例组成的列表,然后报告创建列表前后内存的用量。

示例 A-4 memtest.py:创建大量 Vector 实例,报告内存用量

import importlib
import sys
import resource

NUM_VECTORS = 10**7

if len(sys.argv) == 2:
    module_name = sys.argv[1].replace('.py', '')
    module = importlib.import_module(module_name)
else:
    print('Usage: {} <vector-module-to-test>'.format())
    sys.exit(1)

fmt = 'Selected Vector2d type: {.__name__}.{.__name__}'
print(fmt.format(module, module.Vector2d))

mem_init = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
print('Creating {:,} Vector2d instances'.format(NUM_VECTORS))

vectors = [module.Vector2d(3.0, 4.0) for i in range(NUM_VECTORS)]

mem_final = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
print('Initial RAM usage: {:14,}'.format(mem_init))
print('  Final RAM usage: {:14,}'.format(mem_final))