Memory Profiler in Visual Studio 2017

Recently I have read some articles talking about memory optimization theoretically, and I am looking for someways to prove that. Then I was told Visual Studio has builtin memory profiler tools, so let’s take a look.

Visual Studio 2017 has “Diagnostic Tools” which will automatically show up when you start debugging.

memoryprofiler1

Using “Heap Profiling” function, we can set breakpoints and take snapshots to monitor the heap memory usage. I have written the code below to test it, with breakpoints on lines 6, 11, 12, 14.

#include "stdafx.h"

int main()
{
	// on stack
	int m = 100;
	int *array;
	int array1[100]; // not on heap

	// on heap
	array = new int[m];
	delete[] array;

	return 0;
}

When we start debugging, the program will pause on each breakpoint, then we can take snapshots accordingly.

memoryprofiler2

The first snapshot was took at the first breakpoint, before the program entered line 6. It shows the initial heap memory usage before we do any real tests.

Then the program declared some local variables, paused at line 11. We can see from the snapshot 2 that the heap memory usage didn’t change. It is because all local variables are on the stack memory, and their space will be automatically released. There is another “Locals” window can keep track local variables.

memoryprofiler3

The line 11 used the “new” operator to allocate some heap memory for the array. So we can see on the snapshot 3, there is one more allocation, and the heap size increased. We can click it to see more details.

memoryprofiler4

Yes we have allocated a int[100] array, and the size should be exactly 4 * 100 = 400 Bytes.

Finally the line 12 deleted the array, so the memory is freed. The heap memory change is exactly opposite to previous one.

memoryprofiler5

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s