3 Replies Latest reply on Oct 2, 2006 3:43 PM by 807607

    System.nanoTime() to measure execution time of an algorithm

    807607
      Would it be advisable to use System.nanoTime() to accurately measure the execution time of an algorithm? I have tried using System.currentTimeMillis() but it always returns me the value ms. (I am trying to measure the execution time for a Binary Search). What worries me is this statement from the API.

      "This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change"

      It would appear that this would not give an accurate measurement of the actual time it takes for the algorithm to execute isn't it?
        • 1. Re: System.nanoTime() to measure execution time of an algorithm
          796447
          Rather than try to find the amount of time it takes on one call (which would normally be a flawed measurement especially if it is very "short", given that the OS clock may not provide granularity down to 1 millesecond, let alone 1 nanosecond), what people normally do is:
          1) Get the current time (in milliseconds or nanoseconds or whatever you want)
          2) Execute the call thousands of times, with the same input and environment (don't sort again what was already sorted, for instance)
          3) Get the current time again
          4) Subtract the times and divide by the number of calls you made

          That's a better measurement
          • 2. Re: System.nanoTime() to measure execution time of an algorithm
            807607
            Rather than try to find the amount of time it takes
            on one call (which would normally be a flawed
            measurement especially if it is very "short", given
            that the OS clock may not provide granularity down to
            1 millesecond, let alone 1 nanosecond), what people
            normally do is:
            1) Get the current time (in milliseconds or
            nanoseconds or whatever you want)
            2) Execute the call thousands of times, with the
            same input and environment
            (don't sort again what
            was already sorted, for instance)
            3) Get the current time again
            4) Subtract the times and divide by the number of
            calls you made

            That's a better measurement
            i will try that out. Thanks alot.
            • 3. Re: System.nanoTime() to measure execution time of an algorithm
              807607
              if you want to use this for benchmarking, don't.

              http://www-128.ibm.com/developerworks/java/library/j-jtp02225.html