开发者

measuring execution time in java [duplicate]

开发者 https://www.devze.com 2023-02-18 01:05 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: Measure execution time for a开发者_如何学编程 Java method
This question already has answers here: Closed 10 years ago.

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?


long startTime = new Date().getTime();
doSomething();
long endTime = new Date().getTime();
System.out.println("elapsed milliseconds: " + (endTime - startTime));


long startTime = System.currentTimeMillis();
//...
long entTime = System.currentTimeMillis();
long spentTime = endTime - startTime;


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


This should work:

System.currentTimeMillis();


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消