import java.nio.charset.CharsetEncoder; import java.nio.charset.Charset; import java.nio.ByteBuffer; import java.nio.CharBuffer; public class ASCIIEncodingBenchmark { long numberOfConversions = 0; CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder(); ByteBuffer bytebuffer; CharBuffer charbuffer; char[] chars; public static void main(String[] args){ ASCIIEncodingBenchmark a = new ASCIIEncodingBenchmark(); a.runTest(Integer.parseInt(args[0])); } public void runTest(int numberOfChars) { System.out.println("Char-Byte Test Start"); //Set variables char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; bytebuffer = ByteBuffer.allocate(numberOfChars); charbuffer = CharBuffer.allocate(numberOfChars); for (int i = 0 ; numberOfChars > i ; i++) charbuffer.append(alphabet[i % 26]); //Start time long start = System.currentTimeMillis(); //Convert chars to bytes for 30 seconds. System.out.println("Warming up for 30 seconds."); long endOfWarmup = start + (30 * 1000); while(endOfWarmup > System.currentTimeMillis()) convertCharToByte(); System.out.println("Warm up is Complete. Beginning test."); //Continue for another 10 seconds, while tracking the number of conversions made. long endOfTest = System.currentTimeMillis() + (10 * 1000); while(endOfTest > System.currentTimeMillis()) { convertCharToByte(); numberOfConversions++; } //Print number of conversions made. System.out.println("After a 30 second warmup, 10 seconds saw " + numberOfConversions + " chars turned into bytes"); //End System.out.println("Char-Byte Test End"); } private void convertCharToByte(){ encoder.reset(); bytebuffer.clear(); charbuffer.position(0); encoder.encode(charbuffer,bytebuffer,true); } }