【发布时间】:2012-11-19 23:17:42
【问题描述】:
我有一个用 C++ 编写的递归函数,它使用new 动态分配二维数组。
如何测量函数在其整个生命周期内在堆和堆栈上分配的空间总量?
这是一个如何测量堆栈的示例(不是我的代码)。
unsigned int maxStackLocation ;
unsigned int minStackLocation ;
main ()
{
//get the address of a local variable before calling Quicksort
//the stack grows down, so this is the max stack location
int localVariable;
void *currPtrLocation = (void*)(&localVariable);
maxStackLocation = *(unsigned int *)(&currPtrLocation);
//we get the value for the minimum stack location in quicksort itself
//call quicksort
Quick (A, num);
space = maxStackLocation - minStackLocation;
}
//some redundant function whose stack usage will be measured
void Quick (unsigned int A[], int num)
{
if (num <= 1)
{
//check the stack usage
//figure out where we are on the stack by looking at the byte
// address of the local variable
//we do this by making a pointer to a local variable, and then
//casting it to a integer
void *currPtrLocation = (void*)(&num);
unsigned int currStackLocation = *(unsigned int*)(&currPtrLocation);
if (currStackLocation < minStackLocation)
minStackLocation = currStackLocation;
return;
}
}
编辑
Borgleader 指出我最初的问题“测量最大空间函数在其整个生命周期内分配在堆和堆栈上”是不正确的。我已将“max”更改为“total”。
【问题讨论】:
-
Scott Meyer 的其中一本书中有一个完整的部分介绍了如何没有可靠的方法来区分堆分配和堆栈分配。您可能可以获得总分配,但您不知道它发生在哪两个中。
-
@Borgleader 好点,我可能会修改我的问题。
-
保留一个全局变量并在有新语句的地方更新它
-
@Borgleader - 请让我知道 Scott Meyer 的哪些书中有这个部分......以及哪个部分?谢谢。
-
@phonetagger: IIRC 在“更有效的 C++”第 27 条:要求或禁止基于堆的对象。
标签: c++ memory-management heap-memory dynamic-memory-allocation stack-memory