Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measuring time differences using System.currentTimeMillis()

Tags:

java

time

I have a simple java program, and I want to know the time difference between some set of operations. For this question the details are not important, but let us take 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 is run on a machine, how reliable will the difference be?

Let us say, that the processor starts executing some instructions from my code, then gives context to another process, which executes for some time, and then comes back to execute instructions related to this java process.

So, the time difference should depend on the current state of my machine, i.e. how many processes are running etc? So, in profiling time it takes for some operations to run, is this mechanism not reliable?

like image 343
Sumeet Khullar Avatar asked Oct 25 '12 05:10

Sumeet Khullar


People also ask

How does system currentTimeMillis () work?

currentTimeMillis() method returns the current time in milliseconds. The unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

What does system currentTimeMillis () return UTC?

json"(February 26, 2019 12:00:00 AM) and that need to be accessed from android app once device's System. currentTimeMillis() returns exact time.

How does system currentTimeMillis work in Java?

Java System currentTimeMillis() Method The currentTimeMillis() method of System class returns current time in format of millisecond. Millisecond will be returned as unit of time.

Is system currentTimeMillis accurate?

System. currentTimeMillis() will give you the most accurate possible elapsed time in milliseconds since the epoch, but System. nanoTime() gives you a nanosecond-precise time, relative to some arbitrary point. Returns the current value of the most precise available system timer, in nanoseconds.


1 Answers

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

Instead use the System.nanoTime() which returns the current value of the most precise 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;
like image 127
icza Avatar answered Oct 18 '22 18:10

icza