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