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