views:

341

answers:

4

Related to my previous question:
Preventing Memory issues when handling large amounts of text

Is there a way to determine how much memory space my program is occupying? I end up processing a large amount of text file and usually store the processed objects in memory. There are times where there will be too much information, and I will run out of memory. I have a solution for avoiding the memory allocation problem, but I only want to use it when necessary, to avoid paging, which will ultimately decrease my performance when it's not necessary. Is there a way to figure out how much memory I am occupying, so that I can page my information only when necessary?

NOTE: I am looking for a solution that my program can utilize to begin paging when necessary.

+1  A: 

You can try GC.GetTotalMemory:

Retrieves the number of bytes currently thought to be allocated. A parameter indicates whether this method can wait a short interval before returning, to allow the system to collect garbage and finalize objects.

The important thing to note is this part: "Retrieves the number of bytes currently thought to be allocated". This means that this method may not be 100% accurate - as long as you know this going in, you should be able to get a rough idea of your virtual memory utilization at a given point in your application execution.

Edit: Let me now offer a different solution that will probably be more productive: use perfmon and the CLR performance counters.

Andrew Hare
>"[...] best available approximation of the number of bytes currently allocated in managed memory" Wont this get the amount of memory used by all managed assemblies?
phsr
Yes it will but only in the current AppDomain. I strongly recommend using perfmon for this kind of thing.
Andrew Hare
+2  A: 

You really need to use a code Profiler. These will tell you exactly what's happening, where the memory is being used up, etc.

FYI: It's rarely where you think it is.

Stephane Grenier
+1: though it doesn't quite satisfy your question (since you want to do it in code), this is still true; profiling should still be one step of your design because it will illuminate aspects of memory usage that might be obscured by code-accessible measurements. For example, `WorkingSet64` includes shared memory, which you may want to subtract from the total when deciding whether to page or not.
Jeff Sternal
+1  A: 
long bytes = System.Diagnostics.Process.GetCurrentProcess().WorkingSet64;
Matt Wrock
A: 

long bytes = System.Diagnostics.Process.GetCurrentProcess().WorkingSet64 for more See Here

Firoz