0

please i need help i am writing this code to be able to display my execution time anytime i run a program but i usually get different time even when its the same input

after importing all this

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;


    /** Class KnuthMorrisPratt **/
    public class Knuth1
    {
        /** Failure array **/
        private int[] failure;
        /** Constructor **/
        public Knuth1(String text, String pat)
        {
            /** pre construct failure array for a pattern **/
            failure = new int[pat.length()];
            fail(pat);
            /** find match **/
            int pos = posMatch(text, pat);
            if (pos == -1)
                System.out.println("\nNo match found");
            else
                System.out.println("\nMatch found at index "+ pos);
        }
        /** Failure function for a pattern **/
        private void fail(String pat)
        {
            int n = pat.length();
            failure[0] = -1;
            for (int j = 1; j < n; j++)
            {
                int i = failure[j - 1];
                while ((pat.charAt(j) != pat.charAt(i + 1)) && i >= 0)
                    i = failure[i];
                if (pat.charAt(j) == pat.charAt(i + 1))
                    failure[j] = i + 1;
                else
                    failure[j] = -1;
            }
        }
        /** Function to find match for a pattern **/
    private int posMatch(String text, String pat)
        {
            int i = 0, j = 0;
            int lens = text.length();
            int lenp = pat.length();
        while (i < lens && j < lenp)
            {
                if (text.charAt(i) == pat.charAt(j))
                {
                    i++;
                    j++;
                }
                else if (j == 0)
                    i++;
                else
                    j = failure[j - 1] + 1;
            }
            return ((j == lenp) ? (i - lenp) : -1);
        }
        /** Main Function **/
        public static void main(String[] args) throws IOException
        {    
//i think its here were i get the input
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in) ));
            System.out.println("Knuth Morris Pratt Test\n");
            System.out.println("\nEnter Text: ");
            String text = br.readLine();
            System.out.print("\nEnter Pattern");
            String pattern = br.readLine();
                double starttime = System.nanoTime();
            Knuth1 kmp = new Knuth1(text, pattern);
                double endtime = System.nanoTime();
                double executiontime = (endtime - starttime )/1000000000;
               // System.out.printf("%.4f","Execution Time = "+ executiontime + " Seconds");
               System.out.print("Execution Time = ");
               System.out.format("%.4f", executiontime);
               System.out.print(" Seconds");
              // System.out.println(starttime);
              // System.out.println(endtime);

                //I love programming with JAVA and Php. It’s fun and interesting.
        }
    }

this code will check an input strings and pick out the unique word and the try to also display the execution time for the program... what i really want now is to make sure the execution time remain the same when i input the same input.

  • 3
    Please see [How do I write a correct micro-benchmark in Java?](https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java). Please see: [Why is “Can someone help me?” not an actual question?](http://meta.stackoverflow.com/q/284236) – Turing85 May 09 '18 at 21:41
  • 2
    A `double` cannot store the nano time with full precision. Nano time is `long` for a reason. Convert to `double` *after* subtracting `starttime` from `endtime`, but before you divide. --- Also, you should never expect the *exact* same run time, even for equal input. Too many things may affect the result. – Andreas May 09 '18 at 21:48
  • Always **search Stack Overflow** thoroughly before posting. With 1.4 *million* Questions on Java found here, you should assume that most any basic question such as this has already been asked and answered. – Basil Bourque May 10 '18 at 00:10

1 Answers1

0

If you don't care about reusing the timed functionality, use System.nanoTime()

    long before;
    long after;

    // Get time before
    before = System.nanoTime();

    // Code you want to execute here

    // Get time after
    after = System.nanoTime();

    // Calculate duration
    long diff = after - before;

You can encapsulate any code you want into a Runnable or using any of Java 8's new Predicate or Function interfaces which are very similar. You can put the code that you want to run in a lambda expression (like an anonymous function) and pass it to a static method that calculates in nanoseconds the amount of time it takes the runnable object to execute.

This is more code than what is necessary, but it reusable in that you don't have to keep writing start = System.currentTimeMillis() or System.nanoTime()and doing arithmetic every time you want to time something. You can put this function in your static library and use it whenever you want.

/**
 * Times a runnable. Note, there
 * is probably overhead associated with
 * creating a Runnable object, but if
 * assume that's constant for all Runnable
 * objects, then we can simply ignore it
 *
 * @param runnable Runnable to run
 * @return Number of nanoseconds it took to run the Runnable
 */
public static long timedAction(Runnable runnable) {

    long before;
    long after;

    before = System.nanoTime();

    runnable.run();

    after = System.nanoTime();

    return after - before;
}

This is how I use this code block:

public static void main(String[] args) throws Exception {

  final int numKeys = 1000000;

  // Builds an AVL tree
  Runnable snippet = () -> {

    Tree<Integer, Object> avl = new AVLTree<>();

    for (int i = 0; i < numKeys; i++) {

      avl.insert(i, i);
    }

  };

  long nanoSecond = Util.timedAction(snippet);

  double seconds = Mathematics.nanosecondsToSeconds(nanoSecond);

  System.out.println(seconds);
}

Output:

0.493316448
  • 1
    I cannot stress enough that writing a microbenchmark is hard. Your answer, for example, does not take into account JIT-compilation/-optimizations. The accepted way for microbenchmarking is using the [Java Microbenchmark Harness](http://openjdk.java.net/projects/code-tools/jmh/). – Turing85 May 09 '18 at 22:02
  • @Turing85 That's fair. I was unaware of that tool. My solution is more of easy to write and reuse development tool for debugging. –  May 09 '18 at 22:20