Breaking News
Home / Java / Java Tutorials / Build a simple Stop Watch Timer

Build a simple Stop Watch Timer

Stop Watch in JavaAt times we need to know how much time is taken to do a Task? This task can be any unit of work e.g. a method, a few lines of code, a long running code etc. This can be helpful to understand time taken to do a Task and tune it for performance reason.

A Simple Stop Watch utility can help here to do this where ever we want to make a time measurement. This utility is Thread Safe and multiple watches can be in used in parallel with no performance impact. Each task that needs to put on a stopwatch  is stored into Hashtable.

To measure the task time, invoke StopWatch.start(“TASK-NAME”);

Then execute the Task and invoke StopWatch.stop(“TASK-NAME”); to stop the watch. The return value of the stop method gives the time it took to execute the task.

Stop Watch Timer Implementation

Simple Stop Watch Implementation

The following is the a simple implementation of a Stop Watch like Timer.

package com.livrona.snippets.util;

import java.util.Hashtable;

/**
 * A simple Stop Watch Implementation. It can be used for various tasks.
 * 
 * @author developerfeed
 * 
 */
public class StopWatch {
	private static final Hashtable<String, Long> tasks = new Hashtable<String, Long>();

	/**
	 * Start the Watch for a Task with Id
	 * 
	 * @param id
	 */
	public static void start(String taskId) {
		tasks.put(taskId, new Long(System.currentTimeMillis()));
	}

	/**
	 * Stop the watch
	 * 
	 * @param id
	 * @return
	 */
	public static long stop(String taskId) {
		return System.currentTimeMillis()
				- ((Long) tasks.remove(taskId)).longValue();
	}

	/**
	 * Dummy Task 1
	 */
	public static void executeTask1() {
		System.out.println("Task 1 done");
	}

	/**
	 * Dummy Task 2
	 */
	public static void executeTask2() {
		System.out.println("Task 2 done");
	}

	/**
	 * Main Test Method
	 * 
	 * @param args
	 */
	public static final void main(String[] args) {
		// Start a global stopwatch
		StopWatch.start("GLOBAL");

		// evaluate time used by task 1
		StopWatch.start("TASK1");
		executeTask1();
		System.out.println("Time elapsed for task 1 : "
				+ StopWatch.stop("TASK1") + "ms");

		// evaluate time used by task 2
		StopWatch.start("TASK2");
		executeTask2();
		System.out.println("Time elapsed for task 2 : "
				+ StopWatch.stop("TASK2") + "ms");

		// Display time elapsed for full processing
		System.out.println("Total processing time : "
				+ StopWatch.stop("GLOBAL") + "ms");
	}
}

 [pb_builder]

Check Also

Have a Question

How to select a JVM Analyzing Tool?

A JVM monitoring tool also know as a Diagnostic might be needed to fine tune …

Leave a Reply