0

I'm doing a Java class project where I created both an array and a linked list from a previous assignment and the second half of the project is this:

Calculate the time (in milliseconds) it takes to add the 5th object to the middle (index 1 or 2) of the ArrayList (1 point)

Calculate the time (in milliseconds) it takes to add the 5th object to the middle (index 1 or 2) of the LinkedList (1 point)

Print out both of these time calculations on the screen to see which one is faster. (the one with less time is faster). Then, write a comment in your code to explain in your own words why one insert was faster than the other insert (1 point)

Here's what I wrote so far:

package pugs;

import java.util.ArrayList;

public class Demo {

public static void main(String[] args) {
    DogNode headObj;
    DogNode nodeObj1;
    DogNode nodeObj2;
    DogNode nodeObj3;
    DogNode nodeObj4;
    DogNode currObj;

    Dog dog1 = new Dog("Todd", 2.1, 21);
    Dog dog2 = new Dog("Nice Pete", 2.3, 25);
    Dog dog3 = new Dog("Pat", 2.0, 18);
    Dog dog4 = new Dog("Ray Smuckles", 1.5, 25);
    Dog dog5 = new Dog("Roast Beef", 2.5, 17);

    headObj = new DogNode(dog1);

    nodeObj1 = new DogNode(dog2);
    headObj.insertAfter(nodeObj1);

    nodeObj2 = new DogNode(dog3);
    nodeObj1.insertAfter(nodeObj2);

    nodeObj3 = new DogNode(dog4);
    nodeObj2.insertAfter(nodeObj3);

    nodeObj4 = new DogNode(dog5);
    headObj.insertAfter(nodeObj4);

    currObj = headObj;
    while (currObj != null) {
        currObj.printNodeData();
        currObj = currObj.getNext();
    }

    ArrayList<Dog> list = new ArrayList<Dog>();

    list.add(dog1);
    list.add(dog2);
    list.add(dog3);
    list.add(dog4);
    list.add(1,dog5);

    }

}

My professor has given this hint:

  long startTime= System.nanoTime();
  //code to insert here
  long endTime = System.nanoTime();
  double difference = (endTime - startTime) / 1e6;
  System.out.println("Time to insert: " + difference + " ms\n");

How do I use this hint code to calculate the time?

nick
  • 1
  • 1
  • 3
  • 4
    That's a strange assignment. Does your professor know that this kind of timing will give results that are near to useless? The size of the problem is to small. –  May 01 '18 at 17:12
  • 3
    [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) – Andy Turner May 01 '18 at 17:12

1 Answers1

0

I would rather recommend using a library such as Dropwizard-metrics where you can make use of Timer to calculate the time and console reporter to print the values in the console. You might as well use other reporters to extract the data points and visualize it.

For further reference , Getting started with dropwizard-metrics

Antariksh
  • 508
  • 8
  • 17