我想在python3的单元测试中计算应用程序的内存消耗。
我试图在一个简单的单元测试中使用tracemaloc模块来获取所需的信息。
但是我不知道如何得到类名。
memory_profile.test_memory_profile.TstClass
给定对象的。
有没有别的办法?
class TstClass(object):
def __init__(self):
self.value = 100
class TestMemUsage(unittest.TestCase):
def test_tracemalloc_single_object(self):
tracemalloc.start(5)
snapshot1 = tracemalloc.take_snapshot()
obj = TstClass()
snapshot2 = tracemalloc.take_snapshot()
stats = snapshot2.compare_to(snapshot1, 'lineno')
stat = stats[2] # Allocation of ExampleClass()
print(stat)
for line in stat.traceback.format(): # Traceback
print(line)
file_path, line_nr = stat.traceback._frames[0]
print('obj={}'.format(obj))
print('file_path={}'.format(file_path))
print('line_nr={}'.format(line_nr))
print('size_diff={}'.format(stat.size_diff))
print('count_diff={}'.format(stat.count_diff))
# How to get the class name of the object here ?
# e.g. memory_profile.test_memory_profile.TstClass
测试输出:
D:\Projekte\python\python_examples\memory_profile\test_stack_overflow.py:18: size=356 B (+356 B), count=2 (+2), average=178 B
File "D:\Projekte\python\python_examples\memory_profile\test_stack_overflow.py", line 18
obj = TstClass()
obj=
file_path=D:\Projekte\python\python_examples\memory_profile\test_stack_overflow.py
line_nr=18
size_diff=356
count_diff=2