Boxiom
Boxiom

Reputation: 2305

Java: Calculate how long sorting an array takes

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!

Upvotes: 0

Views: 7337

Answers (9)

Jj Tuibeo
Jj Tuibeo

Reputation: 773

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.

Upvotes: 5

Marko Topolnik
Marko Topolnik

Reputation: 200168

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.

Upvotes: 4

diy
diy

Reputation: 3610

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

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

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");

Upvotes: 0

assylias
assylias

Reputation: 328618

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?.

Upvotes: 8

Felquir
Felquir

Reputation: 441

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));

    }

}

Upvotes: 0

yogiam
yogiam

Reputation: 168

do it this way :

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

Hope that helps.

Upvotes: 0

Bilbo Baggins
Bilbo Baggins

Reputation: 3019

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.

Upvotes: 0

ahmedalkaff
ahmedalkaff

Reputation: 313

long beforeTime = System.currentTimeMillis();

// Your Code

long afterTime = System.currentTimeMillis();

long diffInMilliSeconds = afterTime- beforeTime;

Upvotes: 1

Related Questions