Path: blob/master/test/jdk/sun/nio/cs/StrCodingBenchmark.java
41152 views
/*1* Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.util.*;24import java.nio.*;25import java.nio.charset.*;26import java.util.concurrent.*;27import java.util.regex.Pattern;2829/**30* Usage: java StringCodingBenchmark31* [-Diterations=N] [-Dsize=N] [-Dsubsize=N] [-Dmaxchar=N]32* [-Dfilter=REGEXP] [-DSecurityManager=true]33*/34public class StrCodingBenchmark {35abstract static class Job {36private final String name;37public Job(String name) { this.name = name; }38public String name() { return name; }39public abstract void work() throws Throwable;40}4142private static void collectAllGarbage() {43final java.util.concurrent.CountDownLatch drained44= new java.util.concurrent.CountDownLatch(1);45try {46System.gc(); // enqueue finalizable objects47new Object() { protected void finalize() {48drained.countDown(); }};49System.gc(); // enqueue detector50drained.await(); // wait for finalizer queue to drain51System.gc(); // cleanup finalized objects52} catch (InterruptedException e) { throw new Error(e); }53}5455/**56* Runs each job for long enough that all the runtime compilers57* have had plenty of time to warm up, i.e. get around to58* compiling everything worth compiling.59* Returns array of average times per job per run.60*/61public static long[] time0(Job ... jobs) throws Throwable {62//final long warmupNanos = 10L * 1000L * 1000L * 1000L;63final long warmupNanos = 100L * 100L;64long[] nanoss = new long[jobs.length];65for (int i = 0; i < jobs.length; i++) {66collectAllGarbage();67long t0 = System.nanoTime();68long t;69int j = 0;70do { jobs[i].work(); j++; }71while ((t = System.nanoTime() - t0) < warmupNanos);72nanoss[i] = t/j;73}74return nanoss;75}7677public static long[] time(Job ... jobs) throws Throwable {7879long[] warmup = time0(jobs); // Warm up run80long[] nanoss = time0(jobs); // Real timing run81long[] milliss = new long[jobs.length];82double[] ratios = new double[jobs.length];8384final String nameHeader = "Method";85final String millisHeader = "Millis";86final String ratioHeader = "Ratio";8788int nameWidth = nameHeader.length();89int millisWidth = millisHeader.length();90int ratioWidth = ratioHeader.length();9192for (int i = 0; i < jobs.length; i++) {93nameWidth = Math.max(nameWidth, jobs[i].name().length());9495milliss[i] = nanoss[i]/(1000L * 1000L);96millisWidth = Math.max(millisWidth,97String.format("%d", milliss[i]).length());9899ratios[i] = (double) nanoss[i] / (double) nanoss[0];100ratioWidth = Math.max(ratioWidth,101String.format("%.3f", ratios[i]).length());102}103String format = String.format("%%-%ds %%%dd %n",104nameWidth, millisWidth);105String headerFormat = String.format("%%-%ds %%%ds%n",106nameWidth, millisWidth);107System.out.printf(headerFormat, "Method", "Millis");108109// Print out absolute and relative times, calibrated against first job110for (int i = 0; i < jobs.length; i++)111System.out.printf(format, jobs[i].name(), milliss[i], ratios[i]);112return milliss;113}114115public static Job[] filter(Pattern filter, Job[] jobs) {116if (filter == null) return jobs;117Job[] newJobs = new Job[jobs.length];118int n = 0;119for (Job job : jobs)120if (filter.matcher(job.name()).find())121newJobs[n++] = job;122// Arrays.copyOf not available in JDK 5123Job[] ret = new Job[n];124System.arraycopy(newJobs, 0, ret, 0, n);125return ret;126}127128static class PermissiveSecurityManger extends SecurityManager {129@Override public void checkPermission(java.security.Permission p) {130}131}132133public static void main(String[] args) throws Throwable {134final int itrs = Integer.getInteger("iterations", 100000);135final int size = Integer.getInteger("size", 2048);136final int subsize = Integer.getInteger("subsize", 128);137final int maxchar = Integer.getInteger("maxchar", 128);138final String regex = System.getProperty("filter");139final Pattern filter = (regex == null) ? null : Pattern.compile(regex);140final boolean useSecurityManager = Boolean.getBoolean("SecurityManager");141if (useSecurityManager)142System.setSecurityManager(new PermissiveSecurityManger());143final Random rnd = new Random();144145for (Charset charset: Charset.availableCharsets().values()) {146if (!("ISO-8859-1".equals(charset.name()) ||147"US-ASCII".equals(charset.name()) ||148charset.newDecoder() instanceof sun.nio.cs.SingleByte.Decoder))149continue;150final String csn = charset.name();151final Charset cs = charset;152final StringBuilder sb = new StringBuilder();153{154final CharsetEncoder enc = cs.newEncoder();155for (int i = 0; i < size; ) {156char c = (char) rnd.nextInt(maxchar);157if (enc.canEncode(c)) {158sb.append(c);159i++;160}161}162}163final String string = sb.toString();164final byte[] bytes = string.getBytes(cs);165166System.out.printf("%n--------%s---------%n", csn);167for (int sz = 4; sz <= 2048; sz *= 2) {168System.out.printf(" [len=%d]%n", sz);169final byte[] bs = Arrays.copyOf(bytes, sz);170final String str = new String(bs, csn);171Job[] jobs = {172new Job("String decode: csn") {173public void work() throws Throwable {174for (int i = 0; i < itrs; i++)175new String(bs, csn);176}},177178new Job("String decode: cs") {179public void work() throws Throwable {180for (int i = 0; i < itrs; i++)181new String(bs, cs);182}},183184new Job("String encode: csn") {185public void work() throws Throwable {186for (int i = 0; i < itrs; i++)187str.getBytes(csn);188}},189190new Job("String encode: cs") {191public void work() throws Throwable {192for (int i = 0; i < itrs; i++)193str.getBytes(cs);194}},195};196time(filter(filter, jobs));197}198}199}200}201202203