I'm running some benchmark tests over my code and I want to make sure a garbage collect doesn't occur during one of my benchmarks because it's cleaning up the mess of a prior test. I figure my best chance of this is to force a collect before starting a benchmark.
So I'm calling GC.Collect() before a benchmark starts but not sure if a collect continues to run in a separate thread, etc and returns immediately. If it does run on a BG thread I want to know how to call it synchronously or a at least wait til it's finished the collect.
Python deletes unwanted objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically frees and reclaims blocks of memory that no longer are in use is called Garbage Collection.
The general advice is that you should not call GC.
There is nothing wrong in calling GC. Collect in BackGround thread. In fact it doesn't makes any difference at all.
As MSDN states - Use this method to try to reclaim all memory that is inaccessible.
Anyway, if it does starts Garbage collection you should wait to all finilizers to finish before start benchmarking.
GC.Collect();
GC.WaitForPendingFinalizers();
Since .NET Framework 4.5 you can specify whether the GC collection should be blocking:
GC.Collect(GC.MaxGeneration, GCCollectionMode.Optimized, blocking: true);
or
GC.Collect(GC.MaxGeneration, GCCollectionMode.Default, blocking: true);
GCCollectionMode.Default
currently defaults to GCCollectionMode.Forced
For more details, see:
MSDN: GC.Collect Method (Int32, GCCollectionMode, Boolean)
MSDN: Induced collections - guide
If you want to benchmark your code, it should be done over a course of many iterations and as an average. You are never guaranteed when GC is run in the first place.
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