Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

StopWatch - Why is my app so slow ??? (See related posts)

StopWatch is a small class allowing to manage multiple concurrent stopwatches to measure time elapsed between two calls. Nothing is done while time is rolling (no thread, no loop), it only stores and compares timestamps.

import java.util.Hashtable;

public class StopWatch {
    private static final Hashtable startTime = new Hashtable();
    
    public static void start(String id){
        startTime.put(id,new Long(System.currentTimeMillis()));
    }

    public static long stop(String id){
        return System.currentTimeMillis() - ((Long)startTime.remove(id)).longValue();
    }
}


Example of use :
public 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";
}

Comments on this post

khattaksd posts on Feb 11, 2007 at 04:13
nice!
snekse posts on Feb 14, 2007 at 10:41
Nice, but the Jakarta Commons version has a bit more functionality.

http://jakarta.apache.org/commons/lang/api-release/org/apache/commons/lang/time/StopWatch.html
nivek posts on Feb 19, 2007 at 05:17
I did not know the Commons version :-) It's easy to add some more functionality to my version, but the goal of this snippet was only to give a realy small and easy time measure tool.

I see a few benefits to my own StopWatch :
- Easy to integrate in any project : no external lib
- Lightweight : only based on static calls to a Hashtable singleton for a full collection of watches (replace the Hashtable with any other Map for better performance)

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts