Skip to content

Instantly share code, notes, and snippets.

@parsons-Jsr
Last active October 12, 2015 14:48
Show Gist options
  • Save parsons-Jsr/4043333 to your computer and use it in GitHub Desktop.
Save parsons-Jsr/4043333 to your computer and use it in GitHub Desktop.
Java- Measuring Iteration time using nanoTime
import java.io.*;
import java.util.*;
class MeasureTime
{
public static void main (String[] args)
{
for (int i=1;i<100;i++)
{
long start_time;
long execution_time;
randomArray ra = new randomArray();
start_time = System.nanoTime();
for (int x=0;x<100;x++)
{
int[] test = ra.randomArray(100);
}
execution_time = System.nanoTime() - start_time;
System.out.println(execution_time);
}
}
}
import java.util.*;
public class randomArray
{
//Constructor takes the integer arguement as the desired length of an array
//The array is randomly occupied with values from 0-100
//The array is returned to be outputted in a separate method
public static int[] randomArray(int arrayLen)
{
//Creates array of length [passed in value]
int[] randArr;
randArr = new int[arrayLen];
//Creates random number generator
Random randomGenerator = new Random();
//Occupies objects in array with values 0-100 using the random number generator
for(int i=0; i<(arrayLen-1); i++)
{
int randx = randomGenerator.nextInt(100);
randArr[i] = randx;
}
//Generated array is returned
return randArr;
}
//Method passes a user inputed integer into the constructor
//The created array is outputted to the terminal
public static int[] resultOutput()
{
//Asks for user input and converts it from a string to an integer
Scanner user_input = new Scanner(System.in);
System.out.println("Please enter your chosen variable length:\n");
String chosenLenString = user_input.next();
int chosenLenInt = Integer.parseInt(chosenLenString);
//Integer is passed into the constuctor to generate the array
int[] resultArr = randomArray(chosenLenInt);
//Array is outputted to the terminal
System.out.println("An array of length " + chosenLenString + "=\n" + Arrays.toString(resultArr));
return resultArr;
}
public static void main (String[] args)
{
resultOutput();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment