How To Get The Execution Time Of Multiple Methods In Selenium Java? | Devstringx Technologies

Devstringx Technologies
2 min readOct 3, 2021

Before executing the below code, confirm that pom is updated with the specified dependencies or add required jars to Java build path.

We are using the Stopwatch of Apache Commons Lang to count the duration and reporter to log messages which will be included within the HTML reports generated by TestNG. It is necessary to install the TestNG plugin in your IDE.

Add dependencies to pom.xml of the Maven project or download the jars and add them to JAVA build path of the JAVA project.

import org.apache.commons.lang.time.StopWatch;import org.testng.Reporter;public class stopwatchtime extends StopWatch {static StopWatch stopwatch = new StopWatch();public static void timetaken(){long x = stopwatch.getTime();// Convert the result to a stringString numberAsString = Long.toString(x);System.out.println(“Execution time for this method- ” +numberAsString+ ” milliseconds \n”);Reporter.log(“Time taken to execute this method- “+numberAsString+” milliseconds \n” );}public static void start(String methodname) {stopwatch.start();Reporter.log(methodname+”; \n”);}public static void stop(String methodname) {stopwatch.stop();Reporter.log(methodname+ “; \n”);}public static void reset(String methodname) {stopwatch.reset();Reporter.log(methodname+”; \n”);}}}

Make sure that you simply have added this code to a separate class “stopwatch time” inside the package where you would like to perform these actions.

Now you’ll call these function multiple times in your main code inside same package:

stopwatchtime.reset(“timer reset”);

stopwatchtime.start(“timer started”);

stopwatchtime.stop(“timer stopped”);

stopwatchtime.timetaken();

To get the execution time of a selected method, call the above functions inside that method in the same fashion.

You can find the log messages within the generated TestNG report i.e. index.html or emailable-report.html

Originally published at https://www.devstringx.com on Sept 03, 2021.

--

--

Devstringx Technologies

Devstringx Technologies is highly recommended IT company for custom software development, mobile app development and automation testing services