previous | start

Application using the StopWatch class type

import java.util.Random;
import java.util.Scanner;

public class RandomApp 
{
  public static void main(String[] args) {
    int n;
    int[] a;
    Scanner in = new Scanner(System.in);
    StopWatch sw = new StopWatch();

    System.out.print("How many random integers? ");
    n = in.nextInt();
    a = new int[n];

    Random r = new Random();
    sw.reset();
    for(int i = 0; i < a.length; i++) {
        a[i] = r.nextInt(100);
    }
    double tm = sw.elapsedTime();
    System.out.printf("Time to initialize array of %d random integers: %f (msec)\n", 
                         n, tm);

    sw.reset();
    double m = Stats.mean(a);
    double sd = Stats.stddev(a);
    tm = sw.elapsedTime();

    System.out.printf("For %d random values: mean = %f, stddev = %f\n", n, m, sd);
    System.out.printf("Elapsed time to calculate mean and stddev: %f (msec)\n", tm);
  }
}


previous | start