Wednesday, February 8, 2023

How to check the total time & total space usage in Java

How to check the total time & total space usage in Java

To check the total time it takes to execute a piece of code in Java, you can use the System.currentTimeMillis() method. Here's an example:

long startTime = System.currentTimeMillis(); // Code to be measured goes here long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; System.out.println("Total time to execute: " + totalTime + " milliseconds");

In this example, the time it takes to execute the code between startTime and endTime is calculated and printed in milliseconds. You can adjust the units of time as needed.


To check the total space usage in Java, you can use the Runtime class, which provides methods to interact with the JVM's runtime environment. Here is an example of how to get the total amount of memory that is currently in use:

Runtime runtime = Runtime.getRuntime(); long totalMemory = runtime.totalMemory(); long freeMemory = runtime.freeMemory(); long usedMemory = totalMemory - freeMemory; System.out.println("Total memory: " + totalMemory / 1024 / 1024 + " MB"); System.out.println("Used memory: " + usedMemory / 1024 / 1024 + " MB");

his code outputs the memory usage in MB. Note that totalMemory gives the size of the current heap, while usedMemory is the actual amount of memory used by the application.

No comments:

Post a Comment

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...