import java.util.Random;

/*
	http://java.sun.com/docs/books/tutorial/java/nutsandbolts/switch.html
	to use this example please use :
		java  -Xmx256m TestInstanceOf
*/
public class TestInstanceof{
	public static void main(String []args){
		int l2n=24;
		if(args.length<=0){
			System.err.println("You need to specify at least to arguments, using the default value 24");
		}else{
		try{
			l2n=Integer.parseInt(args[0]);
		}catch(NumberFormatException e){
			System.err.println("\""+args[0]+"\" seems not to be an integer, using by default 24");
		}
		}
	if(l2n>26){
		System.err.println("Too big argument");
		System.exit(1);
	}
		System.out.println("Testing Speed of instanceOf");
		Object[] data=new Object[1<<22];
		Random r=new Random();
		System.out.println("Creating : "+data.length+" new Objects");
		long starttime=System.nanoTime();
		for(int i=0;i<data.length;i++){
			switch(r.nextInt()%3){
				case 0:data[i]=new String();
				case 1:data[i]=new Double(0);
				case 2:data[i]=new Integer(0);
			}
		}
		long endtime=System.nanoTime();
		System.out.println("Creating elements took : " + String.format("%8.3f",((endtime-starttime)/1000.0/1000.0)) + "ms");
		starttime=endtime;
		int str_count=0,double_count=0,integer_count=0;
		for(int i=0;i<data.length;i++){
			if(data[i] instanceof String){
				str_count++;
			}else if(data[i] instanceof Double){
				double_count++;
			}else{
				integer_count++;
			}
		}
		endtime=System.nanoTime();
		double time=(endtime-starttime);
		System.out.println("Counting elements took : " + String.format("%8.3f",time/1000000.0) + "ms");
		int total=str_count+double_count*2+integer_count*3;
		System.out.println("For a total of "+total+" evaluations)");
		System.out.println(time/total+" ns for each evaluation");
	}
}

