At 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.

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 java4learners
*
*/
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");
}
}
Related Links
- Build a simple Stop Watch Timer
- Write a program to generate Fibonacci Numbers
- Write a program to compute factorial of a number in Java
- Understanding Constructors in Java
- Free Font for Programmers
- Automated Functional Testing
- How to install Microsoft Fonts or True Type fonts in Ubuntu?
- How to use Eclipse for Java Development?
- Load Properties from Classpath
- How to Read a File as Byte Array?

So you are trying to create your own website, and wonder with
Post new comment