开发者

Memory profiler for C [closed]

开发者 https://www.devze.com 2023-02-02 02:53 出处:网络
Closed. This question does not meet Stack Overflow guidelines. It i开发者_开发问答s not currently accepting answers.
Closed. This question does not meet Stack Overflow guidelines. It i开发者_开发问答s not currently accepting answers.

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Closed 4 years ago.

Improve this question

I need a memory profiler to know the memory usage for each function. I know valgrind (Massif) but it doesn't give me information about specific functions (at least, I don't know how to do it with massif)

Do you know any tool for this purpose in Linux?

Thanks!


You may want to take a look at MemProf.


If you just want to get the location from where large amount of memory is requested, The easiest way would be to patch malloc function or create a new library having malloc call and track the size form your malloc function. I am not talking about implementing the malloc call. LD_PRELOAD this library to your application.

here is a sample code:

/*
 * gcc -shared -fPIC foo.c -ldl -Wl,-init,init_lib -o libfoo.so
 *
 * LD_PRELOAD this library in the environment of the target executable
 *
 */

#include <stdio.h>
#include <sys/time.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <sys/errno.h>

#ifndef RTLD_NEXT
#define RTLD_NEXT ((void *)-1)
#endif

int init_lib(void)
{
    return 0;
}

void *malloc(size_t size)
{
    /* do required checks on size here */

    return ((void* (*)(size_t))(dlsym(RTLD_NEXT, "malloc")))(size);
}

You can very well modify this code to do some additional stuff.


Massif does show you which functions were responsible for the memory usage, as long as you've compiled your program with debugging info (-g). It will even show you the line number.

This information is given as a call tree in each detailed snapshot under the graph in the ms_print output. The frequency of detailed snapshots can be controlled with the --detailed-freq option to massif. See Section 9.2.6 of the Massif manual for details on reading the detailed snapshot information.


As others have pointed out Massif gives exhaustive profiling information, but it considerably slows down the process.

Another option is Google's tcmalloc, which has an embedded heap profiler that dumps the call graph with allocations (see http://goog-perftools.sourceforge.net/doc/heap_profiler.html), which can also be visualized graphically.

You can link it at runtime with your program with LD_PRELOAD, and the HEAPPROFILE env variable enables the heap profiler.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号