1

So i have these two codes. One called MyTimer and SortCode. MyTimer Calculated the elapsed time of a piece of code And SortCode reads a file and prints out the sorted code. How do I use MyTimer to find the elapsed time of each sort code.

import java.io.*;
import java.util.*;


public class SortCode
{
    public static void main(String[] args)
    {
        ArrayList<Integer> hold = new ArrayList<Integer>();
        try(
              //Open files
              FileReader reader = new FileReader("TestData.txt");
              Scanner in = new Scanner(reader);
              FileWriter writer = new FileWriter("SortedData.txt");
              PrintWriter out = new PrintWriter(writer);
           )
        {
            while(in.hasNextLine())
            {
                String next = in.nextLine();
                try
                {
                    int n = Integer.parseInt(next);
                    hold.add(n);
                }
                catch(NumberFormatException e)
                {
                    System.out.println("Invalid input " + next);
                }
            }

            insertionSort(hold);
            for(Integer i : hold)
               out.printf("%7d\n", i);
        }
        catch(IOException e)
        {
            System.out.println("Error opening the files." + e);
            System.exit(1);
        }

    }

  public static <T extends Comparable<T>>
  void selectionSort(List<T> table)
  {
     int size = table.size();
     for(int i = 0; i < size - 1; i++)
     {
        int minPos = i;
        T minValue = table.get(i);
        for(int k = i + 1; k < size; k++)
        {
           T nextValue = table.get(k);
           if( nextValue.compareTo(minValue) < 0)
           {
               minPos = k;
               minValue = nextValue;
           }
        }
        if(minPos != i)
        {
           T temp = table.get(i);
           table.set(minPos,temp);
           table.set(i, minValue);
        }
     }
  }


    public static <T extends Comparable<T>>
    int binSearch(ArrayList<T> table, int low, int high, T value)
    {
        while(low <= high)
        {
            int mid = (low + high)/2;
            int result = value.compareTo(table.get(mid));
            if(result  == 0)
              return mid;
            if(result < 0)
              high = mid - 1;
            else low = mid + 1;
        }
        return -low -1;
    }

    public static <T extends Comparable<T>>
    void insertionSort(ArrayList<T> table)
    {
      int size = table.size();
      for(int i = 1; i < size; i++)
      {
         T temp = table.remove(i);
         int pos = binSearch(table, 0, i - 1, temp);
         if(pos < 0)
           pos = -pos - 1;
         table.add(pos, temp);

      }
    }

    public static <T extends Comparable<T>>
    void mergeSort(List<T> table)
    {
      int size = table.size();
      if(size <= 1)
         return;

      int size1 = size/2;
      int size2 = size - size1;
      List<T> v1 = new ArrayList<T>();
      List<T> v2 = new ArrayList<T>();

      for(int i = 0; i < size1; i++)
         v1.add(table.get(i));
      for(int i = 0; i < size2; i++)
         v2.add(table.get(size1 + i));

      mergeSort(v1);
      mergeSort(v2);

      int i1 = 0, i2 = 0;
      int i = 0;
      T value1 = v1.get(i1);
      T value2 = v2.get(i2);

      while(i1 < size1 && i2 < size2)
      {
        if(value1.compareTo(value2) <= 0)
        {
           table.set(i++, value1);
           i1++;
           if(i1 < size1)
             value1 = v1.get(i1);
        }
        else
        {
           table.set(i++, value2);
           i2++;
           if(i2 < size2)
               value2 = v2.get(i2);
        }
      }
      int k;
      if(i1 < size1)
      {
         for(k = i1; k < size1; k++)
            table.set(i++, v1.get(k));
      }
      else
      {
         for(k = i2; k < size2; k++)
           table.set(i++, v2.get(k));
      }
    }

}

And this is MyTimer

public class MyTimer
{
  private long    elapsedTime;
  private long    startTime;
  private boolean on;


  /**
  Create a time in the "not running" state and initialize its elapsed time to zero.
  */
  public MyTimer()
  {
    this.on = false;
    this.elapsedTime = 0L;
  }

  /**
  Change the state of the timer to running, initialize its elapsed time and
  set its start time
  */
  public void start()
  {
    this.on = true;
    this.elapsedTime = 0L;
    this.startTime = System.nanoTime();
  }

  /**
  If the timer is in the running state change its state to "not running" and
  accumulate elapsed time.  If the timer is in the "not running" state stop
  has no effect.
  */
  public void stop()
  {
    if(this.on)
    {
      this.on = false;
      long currentTime = System.nanoTime();
      this.elapsedTime += (currentTime - this.startTime);
    }
  }

  /**
  If the timer is in the "not running" state, change its state to running, but do
  not reset its elapsed time.  New running time will be accumulated with previous
  running time.
  */
  public void resume()
  {
    if(!this.on)
    {
      this.startTime = System.nanoTime();
      this.on = true;
    }
  }

  /**
  Return the elapsed time that this timer has accumulated.  If the
  timer is in the running state, the elapsed time must be calculated.
  If the timer is in the "not running" state the elapsed time was already
  calculated by the stop function.
  */
  public long getElapsedTime()
  {
    if (this.on)
    {
      long currentTime = System.nanoTime();
      this.elapsedTime += (currentTime - this.startTime);
      this.startTime = currentTime;
    }
    return this.elapsedTime;
  }

  /**
  Return elapsed time of the current timer in the form of a string.
  */
  public String toString()
  {
    String result = "" + this.getElapsedTime();
    return result;
  }
}
Kai Wu Toh
  • 236
  • 2
  • 17
Dem
  • 61
  • 8

1 Answers1

1

You can use it like this

MyTimer() timer = new MyTimer(); // create new MyTimer instance 
timer.start(); // start the timer
insertionSort(hold); // run the sorting code here
timer.stop(); // stop the timer
long elapsedTime = timer.getElapsedTime(); // get the elapsed time
Guy
  • 46,488
  • 10
  • 44
  • 88
  • What about the FileReader and Writer – Dem Feb 15 '16 at 06:20
  • @Dem exactly the same way. Create one instance of `MyTimer` and call `start()` and `stop()` before and after every code you want to check. – Guy Feb 15 '16 at 06:24
  • How do I print it? It won't print. – Dem Feb 15 '16 at 15:41
  • @Dem What won't print? – Guy Feb 15 '16 at 17:34
  • the elapsed time also is there a why to change the nanoseconds to milliseconds? – Dem Feb 15 '16 at 17:48
  • @Dem How do you print it? Do you have errors or just nothing is printed? Are you using the same code from my answer? – Guy Feb 15 '16 at 18:12
  • @Dem And to get milliseconds just divide by 1000 `long timeInMiliseconds = timeInNanoSeconds / 1000;` – Guy Feb 15 '16 at 18:14
  • ' MyTimer timer = new MyTimer(); // create new MyTimer instance timer.start(); // start the timer insertionSort(hold); // run the sorting code here timer.stop(); // stop the timer long elapsedTime = timer.getElapsedTime(); // get the elapsed time System.out.print("time is" + timer.getElapsedTime()); ' – Dem Feb 15 '16 at 18:24
  • @Dem I tried this in my computer and it worked fine. Do you have any error? – Guy Feb 15 '16 at 18:36
  • nevermind i figered it out also for the conversion i keep getting an error error: cannot find symbol long timeInMiliseconds = timeInNanoSeconds / 1000; – Dem Feb 15 '16 at 18:40
  • `timeInNanoSeconds` is the variable you want to convert to miliseconds. I'm guessing `elapsedTime` in that case – Guy Feb 15 '16 at 18:43
  • im still getting the time in nano – Dem Feb 15 '16 at 18:47
  • @Dem replace all `System.nanoTime();` with `System.nanoTime() / 1000;` – Guy Feb 15 '16 at 19:06
  • i keep getting numbers like 45 and 57 for the milliseconds is that normal?\ – Dem Feb 15 '16 at 23:16