I wanna do empirical time complexity analysis to a java program. But how do I remove the garbage collection time?
I wanna do empirical time complexity analysis to a java program. But how do I remove the garbage collection time?
You can disable the garbage collector in Java 11+ using the Epsilon No-Op Garbage Collector, introduced in 'JEP 318: Epsilon: A No-Op Garbage Collector (Experimental)'.
Add the following flag to your java command:
java -XX:+UseEpsilonGC ...
Ensure you understand the limitations of this garbage collector flag (explained in the linked JEP). There is one major caveat:
Once the available Java heap is exhausted, the JVM will shut down.
You could try running with the Epsilon GC; see @concision's answer.
But the empirical complexity for a Java program should include the GC overheads. So maybe a better approach is to make your measurements by running your program repeatedly in the same JVM and averaging the times so that the GC overheads are amortized. Consider using a benchmarking framework like JMH.
See the other answers which directly answer your question, but in general if you want to check performance characteristics, the garbage collector is just one of half a billion things that can mess with your timings.
Use JMH, which will try to mitigate or outright eliminate most of those things, and it will take care of waiting out hotspot warmup and the like. Any benchmark not based around JMH or similar is unlikely to mean much.