Dan McClain
Dan McClain

Reputation: 11920

How can I determine how much memory my program is currently occupying

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.

Upvotes: 6

Views: 11510

Answers (4)

Firoz
Firoz

Reputation: 7454

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

Upvotes: 3

Matt Wrock
Matt Wrock

Reputation: 6640

long bytes = System.Diagnostics.Process.GetCurrentProcess().WorkingSet64;

Upvotes: 8

Stephane Grenier
Stephane Grenier

Reputation: 15917

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.

Upvotes: 3

Andrew Hare
Andrew Hare

Reputation: 351446

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.

Upvotes: 5

Related Questions