Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a gen full garbage collection has been triggered between two checkpoints?

I am doing analysis on the time spend in a critical section of code.

//Take a timestamp before
var before = DateTime.UtcNow;

DoCriticalMethod();

//Take a timestamp after
var after = DateTime.UtcNow;

And sometime I have some values clearly higher than others.

I suspect that it is Garbage collection, so I want to correlate the high values with the fact that a Garbage collection occured during the process.

I tried this so far : I take the counter before :

//Take the number before
int gc2CountBefore = GC.CollectionCount(2);

...

//Take the number after
bool hasgc2occured = (GC.CollectionCount(2) - gc2CountBefore) != 0;

Am I doing it in the good way?

like image 411
Thomas Avatar asked Feb 07 '14 16:02

Thomas


People also ask

What triggers a full GC?

The reason that a Full GC occurs is because the application allocates too many objects that can't be reclaimed quickly enough. Often concurrent marking has not been able to complete in time to start a space-reclamation phase.

How do you make sure that the garbage collector is done running when you call GC collect ()?

To be sure you get all of the garbage, you need to perform two collections: GC. Collect(); GC. WaitForPendingFinalizers(); GC.

What is full garbage collection?

Major or Full Garbage Collection: It is said to have occurred when the objects that survived the minor garbage collection are copied into the old generation or permanent generation heap memory are removed.


2 Answers

The "RegisterForFullGCNotification" method registers for a notification to be raised when the runtime senses that a full garbage collection is approaching. There are two parts to this notification: when the full garbage collection is approaching and when the full garbage collection has completed.

To determine when a notification has been raised, use the "WaitForFullGCApproach" and "WaitForFullGCComplete" methods. Typically, you use these methods in a while loop to continually obtain a "GCNotificationStatus" enumeration that shows the status of the notification.

The "WaitForFullGCApproach" and the "WaitForFullGCComplete" methods are designed to work together. Using one without the other can produce indeterminate results.

like image 86
Kostadin Avatar answered Oct 02 '22 16:10

Kostadin


You can prevent your application from garbage collecting during a certain section:

Prevent .NET Garbage collection for short period of time

I'd try that, then profile your code repeatedly. If you don't see as much fluctuation, it might be GC causing it.

like image 22
Curtis Rutland Avatar answered Oct 02 '22 17:10

Curtis Rutland