我有两个问题:
1.)我想以函数的方式对我的代码进行内存分析。代码可以有任何STL容器。在linux中有没有办法做到这一点?
2.)第二个原因是我太天真了!如果我有一个数据结构
template < class T1 > struct somestruct
{
std::set < T1 > v1;
std::vector < T1 > v2;
std::vector < T1 > v3;
};我知道v1,v2和v3的大小,那么我可以根据sizeof(T1)直接计算结构的大小吗,或者我必须注意填充?
发布于 2013-03-19 18:19:05
我更喜欢在linux上使用the valgrind heap profiler:
valgrind --tool=massif ./testprogram然后,
ms_print ./massif.out.16766 # replace with actual generated name19.63^ ###
| #
| # ::
| # : :::
| :::::::::# : : ::
| : # : : : ::
| : # : : : : :::
| : # : : : : : ::
| ::::::::::: # : : : : : : :::
| : : # : : : : : : : ::
| ::::: : # : : : : : : : : ::
| @@@: : : # : : : : : : : : : @
| ::@ : : : # : : : : : : : : : @
| :::: @ : : : # : : : : : : : : : @
| ::: : @ : : : # : : : : : : : : : @
| ::: : : @ : : : # : : : : : : : : : @
| :::: : : : @ : : : # : : : : : : : : : @
| ::: : : : : @ : : : # : : : : : : : : : @
| :::: : : : : : @ : : : # : : : : : : : : : @
| ::: : : : : : : @ : : : # : : : : : : : : : @
0 +----------------------------------------------------------------------->KB 0 29.48
Number of snapshots: 25
Detailed snapshots: [9, 14 (peak), 24]故障会是这样的
--------------------------------------------------------------------------------
n time(B) total(B) useful-heap(B) extra-heap(B) stacks(B)
--------------------------------------------------------------------------------
10 10,080 10,080 10,000 80 0
11 12,088 12,088 12,000 88 0
12 16,096 16,096 16,000 96 0
13 20,104 20,104 20,000 104 0
14 20,104 20,104 20,000 104 0
99.48% (20,000B) (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
->49.74% (10,000B) 0x804841A: main (example.c:20)
|
->39.79% (8,000B) 0x80483C2: g (example.c:5)
| ->19.90% (4,000B) 0x80483E2: f (example.c:11)
| | ->19.90% (4,000B) 0x8048431: main (example.c:23)
| |
| ->19.90% (4,000B) 0x8048436: main (example.c:25)
|
->09.95% (2,000B) 0x80483DA: f (example.c:10)
->09.95% (2,000B) 0x8048431: main (example.c:23)发布于 2013-03-19 18:26:54
结构的直接sizeof()将返回编译时的大小,即它不会考虑容器的实际大小。因此,您可能希望手动迭代每个容器,并将每个元素的大小相加。
但对你来说更简单的方法可能是使用profiler (例如gprof (GNU Profiler))或其他
https://stackoverflow.com/questions/15496427
复制相似问题