please provide me java class with methods "Start" and "Stop" that can be used to measure…
- User
please provide me java class with methods "Start" and "Stop" that can be used to measure time for code block execution . We call Start to start time measurement. And Stop to finalize time measurement. There should be property that tells time taken in milliseconds between Start and Stop call. There should be a property that will tell - if exception occurred between start and stop calls
- Assistant
Here is a simple Java class that you can use to measure the time taken for a code block execution:
public class TimeMeasurement { private long startTime; private long endTime; private boolean isExceptionOccurred; public void start() { startTime = System.currentTimeMillis(); endTime = -1; isExceptionOccurred = false; } public void stop() { endTime = System.currentTimeMillis(); } public void exceptionOccurred() { isExceptionOccurred = true; } public long getTimeTakenInMilliseconds() { if (endTime != -1) { return endTime - startTime; } else { return -1; } } public boolean isExceptionOccurred() { return isExceptionOccurred; } public static void main(String[] args) { // Usage example TimeMeasurement tm = new TimeMeasurement(); tm.start(); try { // Your code block Thread.sleep(1000); } catch (Exception e) { tm.exceptionOccurred(); } tm.stop(); System.out.println("Time taken: " + tm.getTimeTakenInMilliseconds() + " ms"); System.out.println("Exception occurred: " + tm.isExceptionOccurred()); } }