C 中的内存消耗
我想知道如何测量 C 中图形的内存消耗。 使用以下代码,我初始化一个具有 V 个节点且没有边的图:
Graph GRAPHinit(int V)
{
int v;
Graph G = malloc(sizeof *G);
G->V = V; G->E = 0;
G->adj = malloc(V*sizeof(link));
for (v = 0; v < V; v++) G->adj[v] = NULL;
return G;
}
该图是一个结构,表示为邻接列表:
struct graph {
int V;
int E;
link *adj;
};
typedef struct node *link;
struct node {
int v;
link next;
};
typedef struct graph *Graph
是否可以使用 sizeof-Operator 来测量 G 使用的空间量? 其他可能性?
I would like to know how to measure the memory consumption of a graph in C.
With the following Code I initialize a Graph with V nodes and no Edges:
Graph GRAPHinit(int V)
{
int v;
Graph G = malloc(sizeof *G);
G->V = V; G->E = 0;
G->adj = malloc(V*sizeof(link));
for (v = 0; v < V; v++) G->adj[v] = NULL;
return G;
}
The Graph is a struct, represented as a adjacency list:
struct graph {
int V;
int E;
link *adj;
};
typedef struct node *link;
struct node {
int v;
link next;
};
typedef struct graph *Graph
Is it possible to measure the amount of space G uses with the sizeof-Operator?
Other possibilities?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,您不能纯粹使用 sizeof 运算符来完成此操作,因为它只能用于编译时静态内存分配。
充其量你可以实现一个新功能,例如
No, you cannot do it purely with the sizeof-operator as this can only be used for compile-time, static memory allocations.
At best you can implement a new function like
这取决于您想要测量的内容:
a) 由该图
malloc
分配的内存b) 由于分配图而导致的程序内存消耗
对于a),只需计算每种类型节点的数量并乘以每种类型的sizeofs 即可。对于 b),您可以计算 a),然后查看 malloc() 的实现以了解它在幕后的作用。还有其他技术,例如往往需要大量努力来验证的黑盒策略。
It depends on what you are trying to measure:
a) memory
malloc
ed by this graphb) program memory consumption due to allocating a graph
For a), just count up the number of each kind of node and multiply by the sizeofs of each type. For b), you could compute a) and then look at the implementation of
malloc()
to see what it does behind the scenes. There are other techniques, such as black box strategies which tend to require a lot of effort to validate.G是2个整数和一个指针。
指针指向的每个结构都包含一个 int 和另一个指针。
在 32 位域中,G 为 12 字节,每个链路为 8 字节。这没有计算每个 malloc() 所带来的额外开销,也没有考虑到 malloc() 实际上不必为每个结构分配如此小的内存块。 。
简而言之,如果您想要精确的大小,您需要自己测量,或者使用您自己的特殊分配器从池中分配。
G is 2 integers and a pointer.
Each struct the pointer points at contains an
int
and another pointer.In 32-bit land, 12 bytes for G and 8 bytes for each link. That does not count the extra overhead that each
malloc()
entails, nor the fact thatmalloc()
does not in fact have to allocate such small chunks of memory for each struct.Short answer, you need to measure this yourself or allocate with your own special allocator from a pool if you want exact sizes.