Getting the memory usage

Started by
13 comments, last by podferio 13 years, 9 months ago
Hi everyone, im having a problem in getting the memory usage of my program. I want to know how much memory was used (in bytes or kb ) in this function:

eg:

int test(int a , int b)
{

// Start
while ( a != b ) {
//..
//..
//..

b++;


// end
}

}

Is it possible to get the memory usage from Start to End as shown in the code.
I heard about GetProcessMemoryInfo() but i dont know how to use it. Help please? Anyone?


Thanks :)
Advertisement
The way I've seen most games do it is to keep track of it yourself. That is, you replace malloc/new/etc with your own versions which increment counters as well as performing an allocation.
If you didn't want to do custom allocation, you could use GetProcessMemoryInfo as you said.

Example:
#include <iostream>#include "windows.h"#include "Psapi.h"using namespace std;int getTotalMemory() {    PROCESS_MEMORY_COUNTERS mem;    GetProcessMemoryInfo(GetCurrentProcess(), &mem, sizeof(mem));    return mem.WorkingSetSize;}int main() {    int startMemory = getTotalMemory();    char* bytes = new char[12345678];  // Allocate some memory    int endMemory = getTotalMemory();    cout << "Memory used = " << endMemory - startMemory;}/* Compiled with: cl <file> /link PsApi.lib */


Not sure if that suits your purpose, but it should get the total working set size of your process
[Window Detective] - Windows UI spy utility for programmers
Thanks you guys for ur help..:D

btw Xtal, what is the unit of measurement? is it in bytes or kb or something?

MSDN
Thx Plerion.

btw

i have an error

>>error LNK2019: unresolved external symbol _GetProcessMemoryInfo@12 referenced in function "int __cdecl getTotalMemory(void)" (?getTotalMemory@@YAHXZ)
>>fatal error LNK1120: 1 unresolved externals

im using MSVS2008


You need to link with Psapi.lib
Quote:Original post by podferio
btw Xtal, what is the unit of measurement? is it in bytes or kb or something?


PROCESS_MEMORY_COUNTERS gives values in bytes.
Already linked the Psapi.lib but i still got the same error. Any more suggestions? :)
Quote:Original post by podferio
Already linked the Psapi.lib but i still got the same error. Any more suggestions? :)


Looks like you need to link kernel.lib on windows 7, are you using windows 7? If not, what method did you use to link psapi.lib? If all else fails perhaps try a rebuild instead of just a regular build.

This topic is closed to new replies.

Advertisement