Home | History | Annotate | Download | only in perf-tests
      1 #!/usr/local/bin/perl
      2 # *  2016 and later: Unicode, Inc. and others.
      3 # * License & terms of use: http://www.unicode.org/copyright.html#License
      4 # *******************************************************************************
      5 # * Copyright (C) 2002-2007 International Business Machines Corporation and     *
      6 # * others. All Rights Reserved.                                                *
      7 # *******************************************************************************
      8 
      9 use strict;
     10 
     11 # Assume we are running within the icu4j root directory
     12 use lib 'src/com/ibm/icu/dev/test/perf';
     13 use Dataset;
     14 
     15 #---------------------------------------------------------------------
     16 # Test class
     17 my $TESTCLASS = 'com.ibm.icu.dev.test.perf.ConverterPerformanceTest';
     18 
     19 # Methods to be tested.  Each pair represents a test method and
     20 # a baseline method which is used for comparison.
     21 my @METHODS  = (
     22 ##               ['TestByteToCharConverter', 'TestByteToCharConverterICU'],
     23 ##               ['TestCharToByteConverter', 'TestCharToByteConverterICU'],
     24                  ['TestCharsetDecoder',      'TestCharsetDecoderICU'],
     25                  ['TestCharsetEncoder',      'TestCharsetEncoderICU']
     26                );
     27 
     28 # Patterns which define the set of characters used for testing.
     29 
     30 my $SOURCEDIR ="src/com/ibm/icu/dev/test/perf/data/conversion/";
     31 
     32 my @OPTIONS = (
     33 #                                 src text          src encoding    test encoding  
     34                                 [ "arabic.txt",     "UTF-8",        "csisolatinarabic"],
     35                                 [ "french.txt",     "UTF-8",        "csisolatin1"],
     36                                 [ "greek.txt",      "UTF-8",        "csisolatingreek"],
     37                                 [ "hebrew.txt",     "UTF-8",        "csisolatinhebrew"],
     38 #                               [ "hindi.txt" ,     "UTF-8",        "iscii"],
     39                                 [ "japanese.txt",   "UTF-8",        "EUC-JP"],
     40 #                               [ "japanese.txt",   "UTF-8",        "csiso2022jp"],
     41                                 [ "japanese.txt",   "UTF-8",        "shift_jis"],
     42 #                               [ "korean.txt",     "UTF-8",        "csiso2022kr"],
     43                                 [ "korean.txt",     "UTF-8",        "EUC-KR"],
     44                                 [ "s-chinese.txt",  "UTF-8",        "EUC_CN"],
     45                                 [ "arabic.txt",     "UTF-8",        "UTF-8"],
     46                                 [ "french.txt",     "UTF-8",        "UTF-8"],                                
     47                                 [ "greek.txt",      "UTF-8",        "UTF-8"],
     48                                 [ "hebrew.txt",     "UTF-8",        "UTF-8"],
     49                                 [ "hindi.txt" ,     "UTF-8",        "UTF-8"],
     50                                 [ "japanese.txt",   "UTF-8",        "UTF-8"],
     51                                 [ "korean.txt",     "UTF-8",        "UTF-8"],
     52                                 [ "s-chinese.txt",  "UTF-8",        "UTF-8"],
     53                                 [ "french.txt",     "UTF-8",        "UTF-16BE"],
     54                                 [ "french.txt",     "UTF-8",        "UTF-16LE"],
     55                                 [ "english.txt",    "UTF-8",        "US-ASCII"],
     56                           );
     57 
     58 my $CALIBRATE = 2;  # duration in seconds for initial calibration
     59 my $DURATION  = 10; # duration in seconds for each pass
     60 my $NUMPASSES = 4;  # number of passes.  If > 1 then the first pass
     61                     # is discarded as a JIT warm-up pass.
     62 
     63 my $TABLEATTR = 'BORDER="1" CELLPADDING="4" CELLSPACING="0"';
     64 
     65 my $PLUS_MINUS = "±";
     66 
     67 if ($NUMPASSES < 3) {
     68     die "Need at least 3 passes.  One is discarded (JIT warmup) and need two to have 1 degree of freedom (t distribution).";
     69 }
     70 
     71 my $OUT; # see out()
     72 
     73 main();
     74 
     75 #---------------------------------------------------------------------
     76 # ...
     77 sub main {
     78     my $date = localtime;
     79     my $title = "ICU4J Performance Test $date";
     80 
     81     my $html = $date;
     82     $html =~ s/://g; # ':' illegal
     83     $html =~ s/\s*\d+$//; # delete year
     84     $html =~ s/^\w+\s*//; # delete dow
     85     $html = "perf $html.html";
     86 
     87     open(HTML,">$html") or die "Can't write to $html: $!";
     88 
     89     print HTML <<EOF;
     90 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
     91    "http://www.w3.org/TR/html4/strict.dtd">
     92 <HTML>
     93    <HEAD>
     94       <TITLE>$title</TITLE>
     95    </HEAD>
     96    <BODY>
     97 EOF
     98     print HTML "<H1>$title</H1>\n";
     99 
    100     print HTML "<H2>$TESTCLASS</H2>\n";
    101 
    102     my $raw = "";
    103 
    104     for my $methodPair (@METHODS) {
    105 
    106         my $testMethod = $methodPair->[0];
    107         my $baselineMethod = $methodPair->[1];
    108 
    109         print HTML "<P><TABLE $TABLEATTR><TR><TD>\n";
    110         print HTML "<P><B>$testMethod vs. $baselineMethod</B></P>\n";
    111         
    112         print HTML "<P><TABLE $TABLEATTR BGCOLOR=\"#CCFFFF\">\n";
    113         print HTML "<TR><TD>Options</TD><TD>$testMethod</TD>";
    114         print HTML "<TD>$baselineMethod</TD><TD>Ratio</TD></TR>\n";
    115 
    116         $OUT = '';
    117 
    118         for my $pat (@OPTIONS) {
    119             print HTML "<TR><TD>@$pat[0], @$pat[2]</TD>\n";
    120 
    121             out("<P><TABLE $TABLEATTR WIDTH=\"100%\">");
    122 
    123             # measure the test method
    124             out("<TR><TD>");
    125             print "\n$testMethod [@$pat]\n";
    126             my $t = measure2($testMethod, $pat, -$DURATION);
    127             out("</TD></TR>");
    128             print HTML "<TD>", formatSeconds(4, $t->getMean(), $t->getError);
    129             print HTML "/event</TD>\n";
    130 
    131             # measure baseline method
    132             out("<TR><TD>");
    133             print "\n$baselineMethod [@$pat]\n";
    134             my $b = measure2($baselineMethod, $pat, -$DURATION);
    135             out("</TD></TR>");
    136             print HTML "<TD>", formatSeconds(4, $b->getMean(), $t->getError);
    137             print HTML "/event</TD>\n";
    138 
    139             out("</TABLE></P>");
    140 
    141             # output ratio
    142             my $r = $t->divide($b);
    143             my $mean = $r->getMean() - 1;
    144             my $color = $mean < 0 ? "RED" : "BLACK";
    145             print HTML "<TD><B><FONT COLOR=\"$color\">", formatPercent(3, $mean, $r->getError);
    146             print HTML "</FONT></B></TD></TR>\n";
    147         }
    148 
    149         print HTML "</TABLE></P>\n";
    150 
    151         print HTML "<P>Raw data:</P>\n";
    152         print HTML $OUT;
    153         print HTML "</TABLE></P>\n";
    154     }
    155 
    156     print HTML <<EOF;
    157    </BODY>
    158 </HTML>
    159 EOF
    160     close(HTML) or die "Can't close $html: $!";
    161 }
    162 
    163 #---------------------------------------------------------------------
    164 # Append text to the global variable $OUT
    165 sub out {
    166     $OUT .= join('', @_);
    167 }
    168 
    169 #---------------------------------------------------------------------
    170 # Append text to the global variable $OUT
    171 sub outln {
    172     $OUT .= join('', @_) . "\n";
    173 }
    174 
    175 #---------------------------------------------------------------------
    176 # Measure a given test method with a give test pattern using the
    177 # global run parameters.
    178 #
    179 # @param the method to run
    180 # @param the pattern defining characters to test
    181 # @param if >0 then the number of iterations per pass.  If <0 then
    182 #        (negative of) the number of seconds per pass.
    183 #
    184 # @return a Dataset object, scaled by iterations per pass and
    185 #         events per iteration, to give time per event
    186 #
    187 sub measure2 {
    188     my @data = measure1(@_);
    189     my $iterPerPass = shift(@data);
    190     my $eventPerIter = shift(@data);
    191 
    192     shift(@data) if (@data > 1); # discard first run
    193 
    194     my $ds = Dataset->new(@data);
    195     $ds->setScale(1.0e-3 / ($iterPerPass * $eventPerIter));
    196     $ds;
    197 }
    198 
    199 #---------------------------------------------------------------------
    200 # Measure a given test method with a give test pattern using the
    201 # global run parameters.
    202 #
    203 # @param the method to run
    204 # @param the pattern defining characters to test
    205 # @param if >0 then the number of iterations per pass.  If <0 then
    206 #        (negative of) the number of seconds per pass.
    207 #
    208 # @return array of:
    209 #         [0] iterations per pass
    210 #         [1] events per iteration
    211 #         [2..] ms reported for each pass, in order
    212 #
    213 sub measure1 {
    214     my $method = shift;
    215     my $pat = shift;
    216     my $iterCount = shift; # actually might be -seconds/pass
    217 
    218     out("<P>Measuring $method for input file @$pat[0] for encoding @$pat[2] , ");
    219     if ($iterCount > 0) {
    220         out("$iterCount iterations/pass, $NUMPASSES passes</P>\n");
    221     } else {
    222         out(-$iterCount, " seconds/pass, $NUMPASSES passes</P>\n");
    223     }
    224 
    225     # is $iterCount actually -seconds/pass?
    226     if ($iterCount < 0) {
    227 
    228         # calibrate: estimate ms/iteration
    229         print "Calibrating...";
    230         my @t = callJava($method, $pat, -$CALIBRATE, 1);
    231         print "done.\n";
    232 
    233         my @data = split(/\s+/, $t[0]->[2]);
    234         $data[0] *= 1.0e+3;
    235 
    236         my $timePerIter = 1.0e-3 * $data[0] / $data[1];
    237         
    238         # determine iterations/pass
    239         $iterCount = int(-$iterCount / $timePerIter + 0.5);
    240         
    241         out("<P>Calibration pass ($CALIBRATE sec): ");
    242         out("$data[0] ms, ");
    243         out("$data[1] iterations = ");
    244         out(formatSeconds(4, $timePerIter), "/iteration<BR>\n");
    245     }
    246     
    247     # run passes
    248     print "Measuring $iterCount iterations x $NUMPASSES passes...";
    249     my @t = callJava($method, $pat, $iterCount, $NUMPASSES);
    250     print "done.\n";
    251     my @ms = ();
    252     my @b; # scratch
    253     for my $a (@t) {
    254         # $a->[0]: method name, corresponds to $method
    255         # $a->[1]: 'begin' data, == $iterCount
    256         # $a->[2]: 'end' data, of the form <ms> <loops> <eventsPerIter>
    257         # $a->[3...]: gc messages from JVM during pass
    258         @b = split(/\s+/, $a->[2]);
    259         push(@ms, $b[0] * 1.0e+3);
    260     }
    261     my $eventsPerIter = $b[2];
    262 
    263     out("Iterations per pass: $iterCount<BR>\n");
    264     out("Events per iteration: $eventsPerIter<BR>\n");
    265 
    266     my @ms_str = @ms;
    267     $ms_str[0] .= " (discarded)" if (@ms_str > 1);
    268     out("Raw times (ms/pass): ", join(", ", @ms_str), "<BR>\n");
    269 
    270     ($iterCount, $eventsPerIter, @ms);
    271 }
    272 
    273 #---------------------------------------------------------------------
    274 # Invoke java to run $TESTCLASS, passing it the given parameters.
    275 #
    276 # @param the method to run
    277 # @param the number of iterations, or if negative, the duration
    278 #        in seconds.  If more than on pass is desired, pass in
    279 #        a string, e.g., "100 100 100".
    280 # @param the pattern defining characters to test
    281 #
    282 # @return an array of results.  Each result is an array REF
    283 #         describing one pass.  The array REF contains:
    284 #         ->[0]: The method name as reported
    285 #         ->[1]: The params on the '= <meth> begin ...' line
    286 #         ->[2]: The params on the '= <meth> end ...' line
    287 #         ->[3..]: GC messages from the JVM, if any
    288 #
    289 sub callJava {
    290     my $method = shift;
    291     my $pat = shift;
    292     my $n = shift;
    293     my $passes = shift;
    294     
    295     my $fileName = $SOURCEDIR.@$pat[0] ;
    296     my $n = ($n < 0) ? "-t ".(-$n) : "-i ".$n;
    297     
    298     my $cmd = "java -classpath classes $TESTCLASS $method $n -p $passes -f $fileName -e @$pat[1] -T @$pat[2]";
    299     print "[$cmd]\n"; # for debugging
    300     open(PIPE, "$cmd|") or die "Can't run \"$cmd\"";
    301     my @out;
    302     while (<PIPE>) {
    303         push(@out, $_);
    304     }
    305     close(PIPE) or die "Java failed: \"$cmd\"";
    306 
    307     @out = grep(!/^\#/, @out);  # filter out comments
    308 
    309     #print "[", join("\n", @out), "]\n";
    310 
    311     my @results;
    312     my $method = '';
    313     my $data = [];
    314     foreach (@out) {
    315         next unless (/\S/);
    316 
    317         if (/^=\s*(\w+)\s*(\w+)\s*(.*)/) {
    318             my ($m, $state, $d) = ($1, $2, $3);
    319             #print "$_ => [[$m $state $data]]\n";
    320             if ($state eq 'begin') {
    321                 die "$method was begun but not finished" if ($method);
    322                 $method = $m;
    323                 push(@$data, $d);
    324                 push(@$data, ''); # placeholder for end data
    325             } elsif ($state eq 'end') {
    326                 if ($m ne $method) {
    327                     die "$method end does not match: $_";
    328                 }
    329                 $data->[1] = $d; # insert end data at [1]
    330                 #print "#$method:", join(";",@$data), "\n";
    331                 unshift(@$data, $method); # add method to start
    332 
    333                 push(@results, $data);
    334                 $method = '';
    335                 $data = [];
    336             } else {
    337                 die "Can't parse: $_";
    338             }
    339         }
    340 
    341         elsif (/^\[/) {
    342             if ($method) {
    343                 push(@$data, $_);
    344             } else {
    345                 # ignore extraneous GC notices
    346             }
    347         }
    348 
    349         else {
    350             die "Can't parse: $_";
    351         }
    352     }
    353 
    354     die "$method was begun but not finished" if ($method);
    355 
    356     @results;
    357 }
    358 
    359 #|#---------------------------------------------------------------------
    360 #|# Format a confidence interval, as given by a Dataset.  Output is as
    361 #|# as follows:
    362 #|#   241.23 - 241.98 => 241.5 +/- 0.3
    363 #|#   241.2 - 243.8 => 242 +/- 1
    364 #|#   211.0 - 241.0 => 226 +/- 15 or? 230 +/- 20
    365 #|#   220.3 - 234.3 => 227 +/- 7
    366 #|#   220.3 - 300.3 => 260 +/- 40
    367 #|#   220.3 - 1000 => 610 +/- 390 or? 600 +/- 400
    368 #|#   0.022 - 0.024 => 0.023 +/- 0.001
    369 #|#   0.022 - 0.032 => 0.027 +/- 0.005
    370 #|#   0.022 - 1.000 => 0.5 +/- 0.5
    371 #|# In other words, take one significant digit of the error value and
    372 #|# display the mean to the same precision.
    373 #|sub formatDataset {
    374 #|    my $ds = shift;
    375 #|    my $lower = $ds->getMean() - $ds->getError();
    376 #|    my $upper = $ds->getMean() + $ds->getError();
    377 #|    my $scale = 0;
    378 #|    # Find how many initial digits are the same
    379 #|    while ($lower < 1 ||
    380 #|           int($lower) == int($upper)) {
    381 #|        $lower *= 10;
    382 #|        $upper *= 10;
    383 #|        $scale++;
    384 #|    }
    385 #|    while ($lower >= 10 &&
    386 #|           int($lower) == int($upper)) {
    387 #|        $lower /= 10;
    388 #|        $upper /= 10;
    389 #|        $scale--;
    390 #|    }
    391 #|}
    392 
    393 #---------------------------------------------------------------------
    394 # Format a number, optionally with a +/- delta, to n significant
    395 # digits.
    396 #
    397 # @param significant digit, a value >= 1
    398 # @param multiplier
    399 # @param time in seconds to be formatted
    400 # @optional delta in seconds
    401 #
    402 # @return string of the form "23" or "23 +/- 10".
    403 #
    404 sub formatNumber {
    405     my $sigdig = shift;
    406     my $mult = shift;
    407     my $a = shift;
    408     my $delta = shift; # may be undef
    409     
    410     my $result = formatSigDig($sigdig, $a*$mult);
    411     if (defined($delta)) {
    412         my $d = formatSigDig($sigdig, $delta*$mult);
    413         # restrict PRECISION of delta to that of main number
    414         if ($result =~ /\.(\d+)/) {
    415             # TODO make this work for values with all significant
    416             # digits to the left of the decimal, e.g., 1234000.
    417 
    418             # TODO the other thing wrong with this is that it
    419             # isn't rounding the $delta properly.  Have to put
    420             # this logic into formatSigDig().
    421             my $x = length($1);
    422             $d =~ s/\.(\d{$x})\d+/.$1/;
    423         }
    424         $result .= " $PLUS_MINUS " . $d;
    425     }
    426     $result;
    427 }
    428 
    429 #---------------------------------------------------------------------
    430 # Format a time, optionally with a +/- delta, to n significant
    431 # digits.
    432 #
    433 # @param significant digit, a value >= 1
    434 # @param time in seconds to be formatted
    435 # @optional delta in seconds
    436 #
    437 # @return string of the form "23 ms" or "23 +/- 10 ms".
    438 #
    439 sub formatSeconds {
    440     my $sigdig = shift;
    441     my $a = shift;
    442     my $delta = shift; # may be undef
    443 
    444     my @MULT = (1   , 1e3,  1e6,  1e9);
    445     my @SUFF = ('s' , 'ms', 'us', 'ns');
    446 
    447     # Determine our scale
    448     my $i = 0;
    449     ++$i while ($a*$MULT[$i] < 1 && $i < @MULT);
    450     
    451     formatNumber($sigdig, $MULT[$i], $a, $delta) . ' ' . $SUFF[$i];
    452 }
    453 
    454 #---------------------------------------------------------------------
    455 # Format a percentage, optionally with a +/- delta, to n significant
    456 # digits.
    457 #
    458 # @param significant digit, a value >= 1
    459 # @param value to be formatted, as a fraction, e.g. 0.5 for 50%
    460 # @optional delta, as a fraction
    461 #
    462 # @return string of the form "23 %" or "23 +/- 10 %".
    463 #
    464 sub formatPercent {
    465     my $sigdig = shift;
    466     my $a = shift;
    467     my $delta = shift; # may be undef
    468     
    469     formatNumber($sigdig, 100, $a, $delta) . ' %';
    470 }
    471 
    472 #---------------------------------------------------------------------
    473 # Format a number to n significant digits without using exponential
    474 # notation.
    475 #
    476 # @param significant digit, a value >= 1
    477 # @param number to be formatted
    478 #
    479 # @return string of the form "1234" "12.34" or "0.001234".  If
    480 #         number was negative, prefixed by '-'.
    481 #
    482 sub formatSigDig {
    483     my $n = shift() - 1;
    484     my $a = shift;
    485 
    486     local $_ = sprintf("%.${n}e", $a);
    487     my $sign = (s/^-//) ? '-' : '';
    488 
    489     my $a_e;
    490     my $result;
    491     if (/^(\d)\.(\d+)e([-+]\d+)$/) {
    492         my ($d, $dn, $e) = ($1, $2, $3);
    493         $a_e = $e;
    494         $d .= $dn;
    495         $e++;
    496         $d .= '0' while ($e > length($d));
    497         while ($e < 1) {
    498             $e++;
    499             $d = '0' . $d;
    500         }
    501         if ($e == length($d)) {
    502             $result = $sign . $d;
    503         } else {
    504             $result = $sign . substr($d, 0, $e) . '.' . substr($d, $e);
    505         }
    506     } else {
    507         die "Can't parse $_";
    508     }
    509     $result;
    510 }
    511 
    512 #eof
    513