확인. 내가 정확히 찾고 있었던 것은 존재하지 않는 것 같습니다. 그래서 해결책을 찾았습니다.이 문제에 대한 해결책입니다.
메모리를 프로파일 링하는 대신 오브젝트를 프로파일 링합니다. 이렇게하면 프로그램의 특정 시간에 얼마나 많은 객체가 있는지 확인할 수 있습니다. 필자의 목표를 달성하기 위해 필자는 기존 코드를 최소한으로 수정하여 메타 클래스를 사용했습니다.
다음 메타 클래스는 클래스의 __init__
및 __del__
함수에 매우 간단한 서브 루틴을 추가합니다. __init__
에 대한 서브 루틴은 해당 클래스 이름을 가진 객체의 수를 1 씩 늘리고 __del__
은 1 씩 감소시킵니다.
class ObjectProfilerMeta(type):
#Just set metaclass of a class to ObjectProfilerMeta to profile object
def __new__(cls, name, bases, attrs):
if name.startswith('None'):
return None
if "__init__" in attrs:
attrs["__init__"]=incAndCall(name,attrs["__init__"])
else:
attrs["__init__"]=incAndCall(name,dummyFunction)
if "__del__" in attrs:
attrs["__del__"]=decAndCall(name,attrs["__del__"])
else:
attrs["__del__"]=decAndCall(name,dummyFunction)
return super(ObjectProfilerMeta, cls).__new__(cls, name, bases, attrs)
def __init__(self, name, bases, attrs):
super(ObjectProfilerMeta, self).__init__(name, bases, attrs)
def __add__(self, other):
class AutoClass(self, other):
pass
return AutoClass
incAndCall 및 decAndCall 함수는 존재하는 모듈의 전역 변수를 사용합니다.
counter={}
def incAndCall(name,func):
if name not in counter:
counter[name]=0
def f(*args,**kwargs):
counter[name]+=1
func(*args,**kwargs)
return f
def decAndCall(name,func):
if name not in counter:
counter[name]=0
def f(*args,**kwargs):
counter[name]-=1
func(*args,**kwargs)
return f
def dummyFunction(*args,**kwargs):
pass
dummyFunction은 아주 간단한 해결 방법입니다. 나는 그것을하는 훨씬 더 좋은 방법이 있다고 확신합니다.
마지막으로, 존재하는 개체의 수를보고 싶을 때마다 카운터 사전을 살펴 봐야합니다. 보기;
>>> class A:
__metaclass__=ObjectProfilerMeta
def __init__(self):
pass
>>> class B:
__metaclass__=ObjectProfilerMeta
>>> l=[]
>>> for i in range(117):
l.append(A())
>>> for i in range(18):
l.append(B())
>>> counter
{'A': 117, 'B': 18}
>>> l.pop(15)
<__main__.A object at 0x01210CB0>
>>> counter
{'A': 116, 'B': 18}
>>> l=[]
>>> counter
{'A': 0, 'B': 0}
이 정보가 도움이되기를 바랍니다. 내 사건으로는 충분했다.
다른 질문에서 해결책에 대해 무엇을 좋아하지 않으세요? – Falmarri
@Falmarri, '메모리'프로파일 러를 찾고 있습니다. 첫 번째는 주로 CPU 프로파일 러입니다. 두 번째 것은 단일 스레드에서만 작동합니다. –
스레드의 주요 특징은 프로세스와 달리 메모리를 공유한다는 것입니다. 같은 메모리를 공유하는 스레드에 대해 서로 다른 메모리 통계를 어떻게 프로파일 링 할 것으로 예상합니까? – scoffey