Calculate Code Execution Time in Spring Boot

Calculate Code Execution Time in Spring Boot | To calculate code execution time in Spring Boot we can use the StopWatch class. This is a class given by Spring F/w in org.springframework.util package to calculate the time taken for task/block/method/object creation etc. Methods:-

  • start(): It will start time counting
  • start(taskName):- Start time counting and assign task name
  • stop(): It will stop time counting
  • getTotalTimeMillis(): return long
  • getTotalTimeSeconds(): return int
  • prettyPrint(): return String

Time Factor Scale:-

  • NANO_SCALE = 1L;
  • MICRO_SCALE = 1000L * NANO_SCALE;
  • MILLI_SCALE = 1000L * MICRO_SCALE;
  • SECOND_SCALE = 1000L * MILLI_SCALE;
  • MINUTE_SCALE = 60L * SECOND_SCALE;
  • HOUR_SCALE = 60L * MINUTE_SCALE;
  • DAY_SCALE = 24L * HOUR_SCALE;

How to use the stopwatch:-

StopWatch stopWatch = new StopWatch();
stopWatch.start();
// code 
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeMillis());

Example:-

package com.knowprogram.demo;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Component
public class TimeTestRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            Math.sqrt(i);
        }
        stopWatch.stop();
        System.out.println("Total time in milli seconds: " 
                + stopWatch.getTotalTimeMillis());
        System.out.println("Total time in seconds: " 
                + stopWatch.getTotalTimeSeconds());
    }

}

Output:-

Assume we have 3 parts of the code and we want to calculate execution time only for 1st and 3rd parts then we can use stop() and again() to resume the calculation.

package com.knowprogram.demo;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Component
public class TimeTestRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        StopWatch watch = new StopWatch("Time Test For Loops"); // Watch#ID
        watch.start("Loop#1"); // Watch#taskName
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            Math.sqrt(i);
            Math.pow(i + 1, 1000);
        }
        watch.stop();

        // skip this part
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            Math.sqrt(i);
        }

        watch.start("Loop#2");
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            Math.sqrt(i);
        }
        watch.stop();

        System.out.println(watch.prettyPrint());
    }

}

Output:-

StopWatch 'Time Test For Loops': 1.5267636 seconds
--------------------------------------------------
Seconds       %       Task name
--------------------------------------------------
0.5137293     34%     Loop#1
1.0130343     66%     Loop#2

IllegalStateException while Using StopWatch

We can’t start the StopWatch which is already running, first we have to stop it. Similarly, we can’t stop the StopWatch which is running stopped.

watch.stop(); // watch stopped
watch.stop(); // exception

IllegalStateException: Can’t stop StopWatch: it’s not running.

watch.start(); // watch started
watch.start(); // exception

IllegalStateException: Can’t start StopWatch: it’s already running.

TimeUnit

While working with StopWatch For time conversion we can use the TimeUnit class of java.util.concurrent package.

package com.knowprogram.demo;

import java.util.concurrent.TimeUnit;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class TimeTestRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        // 3 days-> hours
        System.out.println(TimeUnit.DAYS.toHours(3));
        // 3 days-> mins
        System.out.println(TimeUnit.DAYS.toMinutes(3));
        // 1 sec-> nano sec
        System.out.println(TimeUnit.SECONDS.toNanos(1));
        // 10 min-> mill sec
        System.out.println(TimeUnit.MINUTES.toMillis(10));
    }

}

Output:-

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *