-1

Possible Duplicate:
Measure execution time for a Java method

I would like to test my app, I know there's a certain method in java that returns the execution time but I couldn't find it. Any hints?

Community
  • 1
  • 1
yotamoo
  • 5,334
  • 13
  • 49
  • 61

7 Answers7

2
long startTime = new Date().getTime();
doSomething();
long endTime = new Date().getTime();
System.out.println("elapsed milliseconds: " + (endTime - startTime));
splash
  • 13,037
  • 1
  • 44
  • 67
1
long startTime = System.currentTimeMillis();
//...
long entTime = System.currentTimeMillis();
long spentTime = endTime - startTime;
Aleksejs Mjaliks
  • 8,647
  • 6
  • 38
  • 44
1
long start = System.currentTimeMillis();
//long start = System.nanoTime();
long end = System.currentTimeMillis();
//long end = System.nanoTime();
System.out.println("time diff = " + (end - start) + " ms");

you can use nanoTime() instead of currentTimeMillis() for extra accuracy more discussion about this here

Community
  • 1
  • 1
Ahmed Kotb
  • 6,269
  • 6
  • 33
  • 52
0
long start, end, total;

start = System.currentTimeMillis();
// do stuff   
end = System.currentTimeMillis();

total = end - start;

total will contain the time to run through the main section of your code in milliseconds.

adarshr
  • 61,315
  • 23
  • 138
  • 167
thomson_matt
  • 7,473
  • 3
  • 39
  • 47
0

This should work:

System.currentTimeMillis();
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

I'm not a Java expert but I don't think there is such function. What can you do is to check the system time before and after the bits of code you with to test.& This is one useful implementation.

Samih3
  • 184
  • 3
  • 9
0

You can get a current snapshot of the system time with System.currentTimeMillis().

If you're looking to generate more complicated performance statistics than just timing a single block of code, I'd take a look at the perf4j library. It provides tools for logging performance stats and generating aggregated statistics like mean, min and max times.

ataylor
  • 64,891
  • 24
  • 161
  • 189