0

I am practically checking how much time taking by collection(s) insertion with 'N' elements,

Now I am stuck in checking total time taken by ArrayList in Insertion process.

Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis());
    System.out.println("Start Insertion :: "+startTimeStamp);

    List<Integer> intList = new ArrayList<>();
    for (int i = 0; i <= 100000000; i++) {
        intList.add(i);
    }
    Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
    System.out.println("End insertion :: "+endTimeStamp);
    // Total time taken 
    // TODO       

Output : Start Insertion :: 2020-03-19 16:47:27.395 End insertion :: 2020-03-19 16:48:11.963

Uday Kiran
  • 487
  • 2
  • 9
  • 29
  • 1
    You're making a few mistakes here. 1. You shouldn't be using java.sql.Timestamps. 2. That is not how you write benchmarks, what you're doing won't produce any reasonable results. If you want to learn more, read [this](https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java). In new Java versions there is a build-in framework for writing benchmarks, there are great tutorial on that topic, eg. [here](https://mkyong.com/java/java-jmh-benchmark-tutorial/) – Amongalen Mar 19 '20 at 11:51
  • I recommend you don’t use `Timestamp`. That class is poorly designed and long outdated. Depending on your exact needs you may consider `Instant` and `Duration`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 19 '20 at 15:59

1 Answers1

1

The simple, old-school way would be to use the getTime() method on each Timestamp and subtract the results, giving you the number of milliseconds elapsed between the two:

long millisElapsed = endTimeStamp.getTime() - startTimeStamp.getTime();

Using more modern APIs, though, you would probably convert each timestamp to an Instant, and compute the Duration bracketed by those:

Duration elapsedDuration =
        Duration.between(startTimeStamp.toInstant(), endTimeStamp.toInstant());

A Duration has considerably more structure and support than a primitive long, but perhaps it's more than you need.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157