measure how long a code take to executes with System.currentTimeMillis()
hi,
I have this piece of code
start = System.currentTimeMillis();
// other statetments here, that needed to be measured in time
end = System.currentTimeMillis();
System.out.println(end - start +" msec to run");
is that the right way to do it?
there is also a static method from System class nanoTime(), what is the different? (the api doc is a little difficult to understand cause my english is bad)
--
with currentTimeMillis() as solution I get one time 16 ms and another time 32 ms for the same piece of code,
and when I put a for loop (like 16 times doing the same thing) around the statements that I want to test, there where times that I get runtime as 0 ms,
[788 byte] By [
taisao003a] at [2007-11-26 21:46:53]

That works, but you'll want to
* Make sure that what's between the two curentTimeMillis calls takes at least a second. (100 times the resolution of most system clocks)
* Run the entire thing in a loop a hundreds or thousands of times and look at at least the average, and possibly the min, max, mean, and std dev.
* Understand that your CPU is doing other things besides running your Java program, and even when running your Java program, the VM is doing other things besides executing those statements, so that the time is likely to vary from one execution to the next.
* Understand that hotspot interprets code for a while, and then compiles it, so that the first 10,000 iterations may take longer than the next 100,000.
and also take into consideration that if your code uses any external resources it will spend a lot of time waiting for those resources.
For example, I'm working on a networked solution that needs to talk to a SOAP server to get some information.
We were wondering why it was so terribly slow (calls sometimes took minutes), turned out the SOAP server was so slow, our own code took milliseconds to complete (sometimes within the precision of the currentTimeMillis call) but it regularly has to wait a minute or more for a response from the SOAP service.
If its a plain HelloWorld stuff; the avg time calculated can be taken as a benchmark for most of the platforms. If there is more I/O, Network, or any other system related operations; then the turnaround time depends upon the efficiency of system BUS, FileSystem, OS, Hardware etc.
If you are using a recent JRE (5 or later), I'd recommend using System.nanoTime() as it is specifically intended to measure elapsed time using the highest resolution timer available on the platform (which in some cases will have a better resolution than the one used by System.currentTimeMillis()).
Caveat (from the API doc): "This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. "