Measuring Time Differences Using System.currentTimeMillis ()

I have a simple java program and I want to know the time difference between some sets of operations. Details are not important for this question, but let's look at the following scenario.

long beginTime = System.currentTimeMillis(); //Some operations. Let us asssume some database operations etc. which are time consuming. // long endTime = System.currentTimeMillis(); long difference = endTime - beginTime; 

When the code runs on the machine, how reliable is the difference?

Suppose a processor starts to execute some instructions from my code, and then gives context to another process that has been running for some time, and then returns to execute the instructions associated with this java process.

So, the time difference should depend on the current state of my machine, i.e. on how many processes are running, etc.? So, during profiling, which is required to perform some operations, is this mechanism unreliable?

+7
source share
2 answers

The granularity of System.currentTimeMillis() depends on the implementation and on the operating system and is typically around 10 ms.

Instead, use System.nanoTime() , which returns the current value of the most accurate available system timer in nanoseconds. Note that you can only use this to calculate elapsed time; you cannot use its value as an absolute time.

Example:

 long startTime = System.nanoTime(); // do something you want to measure long elapsedTimeNs = System.nanoTime() - startTime; 
+10
source

I think your code will work fine, as it is used in several projects. I don’t think that if your code invokes some other database process, etc., then this has some effect on your time. In this case, it should work fine.

Ref.

 Main Process Started long beginTime = System.currentTimeMillis(); . . . Called another process (DB or command etc) -> (Another Process start) . <Now in this time main process is waiting> . . . Returned from process <- (Another Process end) . . long endTime = System.currentTimeMillis(); long difference = endTime - beginTime; 

Now this difference will be the total time spent on the main process, including the time spent by another process. This time refers to the machine of the main process, and this is normal.

+2
source

All Articles