Skip to content

Instantly share code, notes, and snippets.

@muthuishere
Created September 21, 2023 11:29
Show Gist options
  • Save muthuishere/1660d515e4a70219e51c9809d7a1cee1 to your computer and use it in GitHub Desktop.
Save muthuishere/1660d515e4a70219e51c9809d7a1cee1 to your computer and use it in GitHub Desktop.
a way to record memory and time in java
public static <T> void recordMemoryUsage(T count,Consumer<T> fn){
Runtime runtime = Runtime.getRuntime();
// Run the garbage collector
runtime.gc();
// Calculate the used memory
long memory = runtime.totalMemory() - runtime.freeMemory();
long startTime = System.nanoTime();
System.out.println("Used memory before operation is: " + memory + " bytes");
// Here run your function for which you want to check the memory usage
fn.accept(count);
// Run the garbage collector
runtime.gc();
// Calculate the used memory
long memoryAfter = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Memory used by memoryafter operation is: " + (memoryAfter ) + " bytes");
System.out.println("Memory used by operation is: " + (memoryAfter - memory) + " bytes");
long endTime = System.nanoTime();
long elapsedTime = endTime - startTime;
double seconds = (double)elapsedTime/1000000000;
System.out.println("Elapsed time: " + seconds + " seconds");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment