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?
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.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With