-1

For some time now I have been using System.nanoTime() in order to measure the time it takes for code to complete. Recently this has become a great disturbance for me. Are there any other ways to measure it?

I am running Java in Eclipse.

Daniel F. Thornton
  • 3,687
  • 2
  • 28
  • 41
user2705335
  • 357
  • 1
  • 3
  • 8

3 Answers3

0
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;    

long time = ManagementFactory.getThreadMXBean().getThreadCpuTime(Thread.currentThread().getId())

JavaDoc

Justin Lessard
  • 10,804
  • 5
  • 49
  • 61
0

You may want to try StatsD:

https://github.com/youdevise/java-statsd-client

Example from the README:

statsd.recordExecutionTime("bag", 25);

bag is the method you would like to record time.

Mingyu
  • 31,751
  • 14
  • 55
  • 60
0

If you dislike typing it out every time, make a class to time it.

Example (static because I'm very lazy; don't want to instantiate an Object):

public static class CodeTimer{
    static long start;
    public static void start(){
        start = System.nanoTime();
    }
    public static void end(){
        System.out.println(System.nanoTime() - end);
        //could easily change it to print out time in seconds, with some
        //String before it, to return a value, etc.
    }
}

This is exactly the same as the System.nanoTime() method, but now you only need to type CodeTimer.start() at the beginning and CodeTimer.end() at the end.

Justin
  • 24,288
  • 12
  • 92
  • 142