how to make a program take time...
Part of my assignment is to make a program where the user chooses 1 of the 7 basic running times and an example program is executed for that running time. Pardon my style as I have not programmed in Java for quite some time...
Code :
import java.util.Scanner;
class Runtimes
{
public static void main(String[]args)
{
String choice;
Scanner scan = new Scanner(System.in);
System.out.println("Enter one of the following:\n 'a' : constant.\n 'b': logarithmic \n 'c': linear\n 'd': n log n\n 'e': quadratic\n 'f': cubic\n 'g': exponential");
choice = scan.nextLine();
long start, end, elapsed;
if(choice.equals("a"))
{
int test;
for(int i = 0; i < 10; i++)
{
start = System.currentTimeMillis();
test = 5 + 8 * 4 + 7;
end = System.currentTimeMillis();
System.out.println( "n = " + i + "elapsed time: " + (end - start));
}
}
if(choice.equals("b"))
{
start = System.currentTimeMillis();
end = System.currentTimeMillis();
}
if(choice.equals("c"))
{
for(int i = 1; i < 10; i++)
{
int [] numbers = new int[i];
start = System.currentTimeMillis();
for(int j = 0; j < i; j++)
{
}
end = System.currentTimeMillis();
System.out.println( "n = " + i + "elapsed time: " + (end - start));
}
}
if(choice.equals("d"))
{
start = System.currentTimeMillis();
end = System.currentTimeMillis();
}
if(choice.equals("e"))
{
start = System.currentTimeMillis();
end = System.currentTimeMillis();
}
if(choice.equals("f"))
{
start = System.currentTimeMillis();
end = System.currentTimeMillis();
}
if(choice.equals("g"))
{
start = System.currentTimeMillis();
end = System.currentTimeMillis();
}
}
}
for now I'm just working with linear and constant... My problem is that each step takes less than a millisecond to execute so it comes out with just 0s. I need to find a way to make it wait. Please help, thanks in advance.
Re: how to make a program take time...
Thread has a static function sleep which allows you to put the current thread to sleep for a specified duration. It takes the number of milliseconds to sleep as the parameter:
Code :
try{
Thread.sleep(1000);//sleep for 1 second
}catch (InterruptedException e){
}