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