Click here to Skip to main content
15,899,754 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I just want to find out the exact execution time of java math functions like Math.sqrt() in the nanosecond range. I have used System.nanoTime() to find the time but it's giving different execution time on each run.

What I have tried:

 I have used System.nanoTime() to find the time but it's giving different execution time on each run.

 code that i have used is:

import java.util.concurrent.TimeUnit;
import java.lang.Math; 

class TimeUtil
{
public static void main(String[] args) throws InterruptedException {

    long startTime = System.nanoTime();

    /* ... the code being measured starts ... */

    Math.sqrt(5.625);

    /* ... the code being measured ends ... */

    long endTime = System.nanoTime();

    // get difference of two nanoTime values
    long timeElapsed = endTime - startTime;

    System.out.println("Execution time in nanoseconds  : " + timeElapsed);

    System.out.println("Execution time in milliseconds : " + 
                            timeElapsed / 1000000);
}
}
Posted
Updated 30-Apr-20 23:46pm

1 solution

Member 14818745 wrote:
it's giving different execution time on each run
You will not find a deterministic relation between a given function and its execution time, as the latter strongly depends on which other processes are running in the machine at the time the function is executed. System.nanoTime is already the most precise form of timer you can get, but precise does not mean constant, it simply means that it has the best time resolution you can get to measure any activity. You can take several measurements and compute their average, if you are not happy with the value returned by a single of them.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900