Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to profile memory usage?

I am aware of Valgrind, but it just detects memory management issues. What I am searching is a tool that gives me an overview, which parts of my program do consume how much memory. A graphical representation with e.g. a tree map (as KCachegrind does for Callgrind) would be cool.

I am working on a Linux machine, so windows tools will not help me very much.

like image 640
math Avatar asked Jan 14 '11 11:01

math


People also ask

How can I track my memory usage?

Press Ctrl + Shift + Esc to launch Task Manager. Or, right-click the Taskbar and select Task Manager. Select the Performance tab and click Memory in the left panel. The Memory window lets you see your current RAM usage, check RAM speed, and view other memory hardware specifications.

How do I run a memory profile in Python?

You can use it by putting the @profile decorator around any function or method and running python -m memory_profiler myscript. You'll see line-by-line memory usage once your script exits.


2 Answers

Use massif, which is part of the Valgrind tools. massif-visualizer can help you graph the data or you can just use the ms_print command.

like image 101
ismail Avatar answered Sep 18 '22 13:09

ismail


Try out the heap profiler delivered with gperftools, by Google. I've always built it from sources, but it's available as a precompiled package under several Linux distros.

It's as simple to use as linking a dynamic library to your executables and running the program. It collects information about every dynamic memory allocation (as far as I've seen) and save to disk a memory dump every time one of the following happens:

  • HEAP_PROFILE_ALLOCATION_INTERVAL bytes have been allocated by the program (default: 1Gb)
  • the high-water memory usage mark increases by HEAP_PROFILE_INUSE_INTERVAL bytes (default: 100Mb)
  • HEAP_PROFILE_TIME_INTERVAL seconds have elapsed (default: inactive)
  • You explicitly call HeapProfilerDump() from your code

The last one, in my experience, is the most useful because you can control exactly when to have a snapshot of the heap usage and then compare two different snapshots and see what's wrong.

Eventually, there are several possible output formats, like textual or graphical (in the form of a directed graph):

Graph of memory usage

Using this tool I've been able to spot incorrect memory usages that I couldn't find using Massif.

like image 43
Paolo M Avatar answered Sep 20 '22 13:09

Paolo M