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?
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.
To be sure you get all of the garbage, you need to perform two collections: GC. Collect(); GC. WaitForPendingFinalizers(); GC.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With