0

I have some code that generates 1000 numbers in an array and then sorts them:

import java.util.Arrays;
import java.util.Random;


public class OppgA {
    public static void main(String[] args) {
        int[] anArray;
        anArray = new int[1000];
        Random generator = new Random();
        for(int i=0; i<1000; i++){
            anArray[i] = (generator.nextInt(1000)+1);
        }
        Arrays.sort(anArray);
        System.out.println(Arrays.toString(anArray));

    }

}

Now I'm asked to calculate and print the time it took to sort the array. Any clues how I can do this? I really couldn't find much by searching that could help me out in my case.

Thanks!

Boxiom
  • 2,245
  • 6
  • 40
  • 51
  • @assylias: you should make that an answer. All the current ones use System.currentTimeMillis(), wich is not the optimal solution. – JB Nizet Aug 22 '13 at 10:12
  • @MarounMaroun: yes indeed: http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/Stopwatch.html :-) – JB Nizet Aug 22 '13 at 10:14
  • @JBNizet LOL. I didn't expect that.. – Maroun Aug 22 '13 at 10:15

9 Answers9

8

You can call (and store the result of) System.nanoTime() before and after the call to Arrays.sort()- the difference is the time spent in nanoseconds. That method is preferred over System.currentTimeMillis to calculate durations.

long start = System.nanoTime();
Arrays.sort(anArray);
long end = System.nanoTime();
long timeInMillis = TimeUnit.MILLISECONDS.convert(end - start, TimeUnit.NANOSECONDS);
System.out.println("Time spend in ms: " + timeInMillis);

But note that the result of your measurement will probably vary widely if you run the program several times. To get a more precise calculation would be more involved - see for example: How do I write a correct micro-benchmark in Java?.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783
5

Before sorting, declare a long which corresponds to the time before you start the sorting:

long timeStarted = System.currentTimeMillis();
//your sorting here.

//after sorting
System.out.println("Sorting last for:" + (System.currentTimeMillis() - timeStarted)); 

The result will return the milli seconds equivalent of your sorting.

As assylias commented you can also use System.nanoTime() if you prefer precise measurements of elapsed time.

Jj Tuibeo
  • 773
  • 4
  • 18
  • 4
    System.nanotime is preferred over System.currentTimeMillis to calculate durations... – assylias Aug 22 '13 at 10:12
  • +1 that is the most basic form of profiling you can add to code...for better results try an even bigger array and sort it.. that will give even better idea of how fast you computer with java is sorting data.. – AurA Aug 22 '13 at 10:13
  • 1
    You are mistaken if you think that `nanoTime` gives a "much accurate" result. The names are misleading: `currentTimeMillis` may report at a granularity of 100ths or even just 10ths of a second. `nanoTime` itself never goes finer than microseconds. – Marko Topolnik Aug 22 '13 at 10:23
  • http://stackoverflow.com/questions/351565/system-currenttimemillis-vs-system-nanotime. you're right. It should be precise not accurate. – Jj Tuibeo Aug 22 '13 at 10:24
4

Proper microbenchmarking is done using a ready-made tool for that purpose, like Google Caliper or Oracle jmh. However, if you want a poor-man's edition, follow at least these points:

  1. measure with System.nanoTime() (as explained elsewhere). Do not trust small numbers: if you get timings such as 10 microseconds, you are measuring a too short timespan. Enlarge the array to get at least into the milliseconds;
  2. repeat the sorting process many times (10, 100 perhaps) and display the timing of each attempt. You are expected to see a marked drop in the time after the first few runs, but after that the timings should stabilize. If you still observe wild variation, you know something's amiss;
  3. to avoid garbage collection issues, reuse the same array, but re-fill it with new random data each time.
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • "repeat the sorting process many times": and discard the first N results to account for warm-up. – Thilo Aug 22 '13 at 10:18
  • @Thilo Personally, I do that step manually. Display all results and *manually* appraise them. The performance jump is easy to spot, as well as any irregularities that may occur. – Marko Topolnik Aug 22 '13 at 10:19
1
long beforeTime = System.currentTimeMillis();

// Your Code

long afterTime = System.currentTimeMillis();

long diffInMilliSeconds = afterTime- beforeTime;
ahmedalkaff
  • 313
  • 1
  • 3
0

before starting the calculation or exactly after generating the array you can use System#currentTimeMillis() to get the exact time and do the same exactly after completion of sorting and then find the difference.

Maroun
  • 94,125
  • 30
  • 188
  • 241
Bilbo Baggins
  • 2,899
  • 10
  • 52
  • 77
0

do it this way :

long start = System.currentTimeMillis(); ... your sorting code ... long end = System.currentTimeMillis(); long timeInMillis = end - start;

Hope that helps.

yogiam
  • 168
  • 7
0
import java.util.Arrays;
import java.util.Random;


public class OppgA {
    public static void main(String[] args) {
        int[] anArray;
        anArray = new int[1000];
        Random generator = new Random();
        for(int i=0; i<1000; i++){
            anArray[i] = (generator.nextInt(1000)+1);
        }
        Date before = new Date();
        Date after;
        Arrays.sort(anArray);
        after = new Date();
        System.out.println(after.getTime()-before.getTime());

        System.out.println(Arrays.toString(anArray));

    }

}
Felquir
  • 431
  • 1
  • 4
  • 12
0

This is not an ideal way. But this will work

    long startingTime=System.currentTimeMillis();
    Arrays.sort(anArray);
    long endTime=System.currentTimeMillis();
    System.out.println("Sorting time: "+(endTime-startingTime)+"ms");

Following can be the best way

    long startingTime=System.nanoTime();
    Arrays.sort(anArray);
    long endTime=System.nanoTime();
    System.out.println("Sorting time: "+(endTime-startingTime)+"ns");
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0

In short, you can either extract our code to a method and than calculate the difference between the timestamps of start and end of that method or you can just run it in a profiler or an IDE and it will print the execution time

Ideally, you should not mix your business logic (array sorting in this case) with 'metrics' stuff.If you do need to measure execution time within the app, you can try to use AOP for that

Please refer to this post , which describes possible solutions in very detail

Community
  • 1
  • 1
diy
  • 3,590
  • 3
  • 19
  • 16