我想知道我的Python应用程序的内存使用情况,并且特别想知道哪些代码块/部分或对象占用了大部分内存.Google搜索显示商业广告是Python Memory Validator(仅限Windows).
我没有尝试任何人,所以我想知道哪一个是最好的考虑:
提供大部分细节.
我必须对代码进行最少或不做任何更改.
我最近对算法感兴趣,并开始通过编写一个简单的实现,然后以各种方式优化它来探索它们.
我已经熟悉用于分析运行时的标准Python模块(对于大多数事情我已经发现IPython中的timeit魔术功能已足够),但我也对内存使用感兴趣,所以我也可以探索这些权衡(例如,缓存先前计算的值表的成本与根据需要重新计算它们的成本.是否有一个模块可以为我分析给定函数的内存使用情况?
我想同时打印我的范围内所有变量的内存大小.
类似的东西:
for obj in locals().values():
print sys.getsizeof(obj)
Run Code Online (Sandbox Code Playgroud)
但是在每个值之前使用变量名称,因此我可以看到我需要删除哪些变量或分成批次.
想法?
我有个问题。我有一个巨大的dict. 我想保存并加载这个巨大的字典。但不幸的是我得到了一个MemoryError. 字典不应该太大。从数据库中读取的内容约为 4GB。我现在想保存这个字典并读出它。但是,它应该是高效的(不会消耗更多内存)并且不会花费太长时间。
目前有哪些选择?我无法进一步了解pickle,出现内存错误。我还剩 200GB 可用磁盘空间。
我查看了用 Python 保存和加载大型字典的最快方法以及其他一些问题和博客。
import pickle
from pathlib import Path
def save_file_as_pickle(file, filename, path=os.path.join(os.getcwd(), 'dict')):
Path(path).mkdir(parents=True, exist_ok=True)
pickle.dump( file, open( os.path.join(path, str(filename+'.pickle')), "wb" ))
save_file_as_pickle(dict, "dict")
[OUT]
---------------------------------------------------------------------------
MemoryError Traceback (most recent call last)
<timed eval> in <module>
~\AppData\Local\Temp/ipykernel_1532/54965140.py in save_file_as_pickle(file, filename, path)
1 def save_file_as_pickle(file, filename, path=os.path.join(os.getcwd(), 'dict')):
2 Path(path).mkdir(parents=True, exist_ok=True)
----> 3 pickle.dump( file, open( os.path.join(path, str(filename+'.pickle')), "wb" ))
MemoryError:
Run Code Online (Sandbox Code Playgroud)
什么有效,但花了 1 小时并且使用了 26GB …
我使用Inspyred库编写了一个用于设计优化的代码及其遗传算法的实现.本质上,优化过程在单个数据结构上创建了大量变体,在我的例子中,这是一个嵌套字典.
为了减少进程中使用的内存量,我一直在尝试创建某种差异字典类型,它只存储与基本字典不同的项目.其原因在于,在典型情况下,数据结构中95%的数据不会在任何变体中被修改,但数据结构的任何部分都可以包含变体.因此,出于灵活性的原因,我希望数据类型的行为或多或少像字典,但只存储更改.
这是我试图创建这个的结果:
#!/usr/bin/python
import unittest
import copy
global_base={}
class DifferentialDict(object):
"""
dictionary with differential storage of changes
all DifferentialDict objects have the same base dictionary
"""
def __init__(self,base=None):
global global_base
self.changes={}
if not base==None:
self.set_base(base)
def set_base(self,base):
global global_base
global_base=copy.deepcopy(base)
def __copy__(self):
return self
def __deepcopy__(self):
new=DifferentialDict()
new.changes=copy.deepcopy(self.changes)
return new
def get(self):
global global_base
outdict=copy.deepcopy(global_base)
for key in self.changes:
outdict[key]=self.changes[key]
return outdict
def __setitem__(self,key,value):
self.changes[key]=value
def __getitem__(self,key):
global global_base
if key in self.changes:
return self.changes[key]
else:
return global_base[key]
class …Run Code Online (Sandbox Code Playgroud) 在 Pycon2016 上观看 Nina Zahkarenko 的 Python 内存管理演讲(链接)后,似乎 dunder 方法__slots__是一种减少对象大小和加速属性查找的工具。
我的期望是普通类将是最大的,而__slots__/namedtuple方法会节省空间。然而,一个快速的实验sys.getsizeof()似乎表明并非如此:
from collections import namedtuple
from sys import getsizeof
class Rectangle:
'''A class based Rectangle, with a full __dict__'''
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
class SlotsRectangle:
'''A class based Rectangle with __slots__ defined for attributes'''
__slots__ = ('x', 'y', 'width', 'height')
def __init__(self, x, y, width, height): …Run Code Online (Sandbox Code Playgroud) 在Pytorch 1.0.0中,我发现一个tensor变量占用的内存很小。我不知道它如何存储这么多数据。这是代码。
a = np.random.randn(1, 1, 128, 256)
b = torch.tensor(a, device=torch.device('cpu'))
a_size = sys.getsizeof(a)
b_size = sys.getsizeof(b)
Run Code Online (Sandbox Code Playgroud)
a_size是262288。b_size是72。
python ×7
dictionary ×2
memory ×2
profiling ×2
class ×1
nested ×1
numpy ×1
performance ×1
pickle ×1
python-3.7 ×1
pytorch ×1
tensor ×1