1 /********************************************************************
3 * Copyright (C) 2001-2011 IBM, Inc. All Rights Reserved.
5 ********************************************************************/
6 /********************************************************************************
10 * Modification History:
12 * Andy Heninger First Version
14 *********************************************************************************
18 // This program tests string collation and sort key generation performance.
19 // Three APIs can be teste: ICU C , Unix strcoll, strxfrm and Windows LCMapString
20 // A file of names is required as input, one per line. It must be in utf-8 or utf-16 format,
21 // and include a byte order mark. Either LE or BE format is OK.
24 const char gUsageString
[] =
25 "usage: collperf options...\n"
26 "-help Display this message.\n"
27 "-file file_name utf-16 format file of names.\n"
28 "-locale name ICU locale to use. Default is en_US\n"
29 "-rules file_name Collation rules file (overrides locale)\n"
30 "-langid 0x1234 Windows Language ID number. Default to value for -locale option\n"
31 " see http://msdn.microsoft.com/library/psdk/winbase/nls_8xo3.htm\n"
32 "-win Run test using Windows native services. (ICU is default)\n"
33 "-unix Run test using Unix strxfrm, strcoll services.\n"
34 "-uselen Use API with string lengths. Default is null-terminated strings\n"
35 "-usekeys Run tests using sortkeys rather than strcoll\n"
36 "-strcmp Run tests using u_strcmp rather than strcoll\n"
37 "-strcmpCPO Run tests using u_strcmpCodePointOrder rather than strcoll\n"
38 "-loop nnnn Loopcount for test. Adjust for reasonable total running time.\n"
39 "-iloop n Inner Loop Count. Default = 1. Number of calls to function\n"
40 " under test at each call point. For measuring test overhead.\n"
41 "-terse Terse numbers-only output. Intended for use by scripts.\n"
42 "-french French accent ordering\n"
43 "-frenchoff No French accent ordering (for use with French locales.)\n"
44 "-norm Normalizing mode on\n"
45 "-shifted Shifted mode\n"
46 "-lower Lower case first\n"
47 "-upper Upper case first\n"
48 "-case Enable separate case level\n"
49 "-level n Sort level, 1 to 5, for Primary, Secndary, Tertiary, Quaternary, Identical\n"
50 "-keyhist Produce a table sort key size vs. string length\n"
51 "-binsearch Binary Search timing test\n"
52 "-keygen Sort Key Generation timing test\n"
53 "-qsort Quicksort timing test\n"
54 "-iter Iteration Performance Test\n"
55 "-dump Display strings, sort keys and CEs.\n"
67 #include <unicode/utypes.h>
68 #include <unicode/ucol.h>
69 #include <unicode/ucoleitr.h>
70 #include <unicode/uloc.h>
71 #include <unicode/ustring.h>
72 #include <unicode/ures.h>
73 #include <unicode/uchar.h>
74 #include <unicode/ucnv.h>
75 #include <unicode/utf8.h>
81 // Stubs for Windows API functions when building on UNIXes.
84 inline int CompareStringW(DWORD
, DWORD
, UChar
*, int, UChar
*, int) {return 0;}
86 unsigned long timeGetTime() {
89 unsigned long val
= t
.tv_sec
* 1000; // Let it overflow. Who cares.
90 val
+= t
.tv_usec
/ 1000;
93 inline int LCMapStringW(DWORD
, DWORD
, UChar
*, int, UChar
*, int) {return 0;}
94 const int LCMAP_SORTKEY
= 0;
95 #define MAKELCID(a,b) 0
96 const int SORT_DEFAULT
= 0;
102 // Command line option variables
103 // These global variables are set according to the options specified
104 // on the command line by the user.
105 char * opt_fName
= 0;
106 const char * opt_locale
= "en_US";
107 int opt_langid
= 0; // Defaults to value corresponding to opt_locale.
108 char * opt_rules
= 0;
109 UBool opt_help
= FALSE
;
110 int opt_loopCount
= 1;
111 int opt_iLoopCount
= 1;
112 UBool opt_terse
= FALSE
;
113 UBool opt_qsort
= FALSE
;
114 UBool opt_binsearch
= FALSE
;
115 UBool opt_icu
= TRUE
;
116 UBool opt_win
= FALSE
; // Run with Windows native functions.
117 UBool opt_unix
= FALSE
; // Run with UNIX strcoll, strxfrm functions.
118 UBool opt_uselen
= FALSE
;
119 UBool opt_usekeys
= FALSE
;
120 UBool opt_strcmp
= FALSE
;
121 UBool opt_strcmpCPO
= FALSE
;
122 UBool opt_norm
= FALSE
;
123 UBool opt_keygen
= FALSE
;
124 UBool opt_french
= FALSE
;
125 UBool opt_frenchoff
= FALSE
;
126 UBool opt_shifted
= FALSE
;
127 UBool opt_lower
= FALSE
;
128 UBool opt_upper
= FALSE
;
129 UBool opt_case
= FALSE
;
131 UBool opt_keyhist
= FALSE
;
132 UBool opt_itertest
= FALSE
;
133 UBool opt_dump
= FALSE
;
138 // Definitions for the command line options
142 enum {FLAG
, NUM
, STRING
} type
;
147 {"-file", OptSpec::STRING
, &opt_fName
},
148 {"-locale", OptSpec::STRING
, &opt_locale
},
149 {"-langid", OptSpec::NUM
, &opt_langid
},
150 {"-rules", OptSpec::STRING
, &opt_rules
},
151 {"-qsort", OptSpec::FLAG
, &opt_qsort
},
152 {"-binsearch", OptSpec::FLAG
, &opt_binsearch
},
153 {"-iter", OptSpec::FLAG
, &opt_itertest
},
154 {"-win", OptSpec::FLAG
, &opt_win
},
155 {"-unix", OptSpec::FLAG
, &opt_unix
},
156 {"-uselen", OptSpec::FLAG
, &opt_uselen
},
157 {"-usekeys", OptSpec::FLAG
, &opt_usekeys
},
158 {"-strcmp", OptSpec::FLAG
, &opt_strcmp
},
159 {"-strcmpCPO", OptSpec::FLAG
, &opt_strcmpCPO
},
160 {"-norm", OptSpec::FLAG
, &opt_norm
},
161 {"-french", OptSpec::FLAG
, &opt_french
},
162 {"-frenchoff", OptSpec::FLAG
, &opt_frenchoff
},
163 {"-shifted", OptSpec::FLAG
, &opt_shifted
},
164 {"-lower", OptSpec::FLAG
, &opt_lower
},
165 {"-upper", OptSpec::FLAG
, &opt_upper
},
166 {"-case", OptSpec::FLAG
, &opt_case
},
167 {"-level", OptSpec::NUM
, &opt_level
},
168 {"-keyhist", OptSpec::FLAG
, &opt_keyhist
},
169 {"-keygen", OptSpec::FLAG
, &opt_keygen
},
170 {"-loop", OptSpec::NUM
, &opt_loopCount
},
171 {"-iloop", OptSpec::NUM
, &opt_iLoopCount
},
172 {"-terse", OptSpec::FLAG
, &opt_terse
},
173 {"-dump", OptSpec::FLAG
, &opt_dump
},
174 {"-help", OptSpec::FLAG
, &opt_help
},
175 {"-?", OptSpec::FLAG
, &opt_help
},
176 {0, OptSpec::FLAG
, 0}
180 //---------------------------------------------------------------------------
182 // Global variables pointing to and describing the test file
184 //---------------------------------------------------------------------------
189 // Each line from the source file (containing a name, presumably) gets
190 // one of these structs.
203 Line
*gFileLines
; // Ptr to array of Line structs, one per line in the file.
214 //---------------------------------------------------------------------------
216 // ProcessOptions() Function to read the command line options.
218 //---------------------------------------------------------------------------
219 UBool
ProcessOptions(int argc
, const char **argv
, OptSpec opts
[])
223 const char *pArgName
;
226 for (argNum
=1; argNum
<argc
; argNum
++) {
227 pArgName
= argv
[argNum
];
228 for (pOpt
= opts
; pOpt
->name
!= 0; pOpt
++) {
229 if (strcmp(pOpt
->name
, pArgName
) == 0) {
230 switch (pOpt
->type
) {
232 *(UBool
*)(pOpt
->pVar
) = TRUE
;
234 case OptSpec::STRING
:
236 if (argNum
>= argc
) {
237 fprintf(stderr
, "value expected for \"%s\" option.\n", pOpt
->name
);
240 *(const char **)(pOpt
->pVar
) = argv
[argNum
];
244 if (argNum
>= argc
) {
245 fprintf(stderr
, "value expected for \"%s\" option.\n", pOpt
->name
);
249 i
= strtol(argv
[argNum
], &endp
, 0);
250 if (endp
== argv
[argNum
]) {
251 fprintf(stderr
, "integer value expected for \"%s\" option.\n", pOpt
->name
);
254 *(int *)(pOpt
->pVar
) = i
;
261 fprintf(stderr
, "Unrecognized option \"%s\"\n", pArgName
);
268 //---------------------------------------------------------------------------------------
270 // Comparison functions for use by qsort.
272 // Six flavors, ICU or Windows, SortKey or String Compare, Strings with length
273 // or null terminated.
275 //---------------------------------------------------------------------------------------
276 int ICUstrcmpK(const void *a
, const void *b
) {
278 int t
= strcmp((*(Line
**)a
)->icuSortKey
, (*(Line
**)b
)->icuSortKey
);
283 int ICUstrcmpL(const void *a
, const void *b
) {
286 t
= ucol_strcoll(gCol
, (*(Line
**)a
)->name
, (*(Line
**)a
)->len
, (*(Line
**)b
)->name
, (*(Line
**)b
)->len
);
287 if (t
== UCOL_LESS
) return -1;
288 if (t
== UCOL_GREATER
) return +1;
293 int ICUstrcmp(const void *a
, const void *b
) {
296 t
= ucol_strcoll(gCol
, (*(Line
**)a
)->name
, -1, (*(Line
**)b
)->name
, -1);
297 if (t
== UCOL_LESS
) return -1;
298 if (t
== UCOL_GREATER
) return +1;
303 int Winstrcmp(const void *a
, const void *b
) {
306 t
= CompareStringW(gWinLCID
, 0, (*(Line
**)a
)->name
, -1, (*(Line
**)b
)->name
, -1);
311 int UNIXstrcmp(const void *a
, const void *b
) {
314 t
= strcoll((*(Line
**)a
)->unixName
, (*(Line
**)b
)->unixName
);
319 int WinstrcmpL(const void *a
, const void *b
) {
322 t
= CompareStringW(gWinLCID
, 0, (*(Line
**)a
)->name
, (*(Line
**)a
)->len
, (*(Line
**)b
)->name
, (*(Line
**)b
)->len
);
327 int WinstrcmpK(const void *a
, const void *b
) {
329 int t
= strcmp((*(Line
**)a
)->winSortKey
, (*(Line
**)b
)->winSortKey
);
334 //---------------------------------------------------------------------------------------
336 // Function for sorting the names (lines) into a random order.
337 // Order is based on a hash of the ICU Sort key for the lines
338 // The randomized order is used as input for the sorting timing tests.
340 //---------------------------------------------------------------------------------------
341 int ICURandomCmp(const void *a
, const void *b
) {
342 char *ask
= (*(Line
**)a
)->icuSortKey
;
343 char *bsk
= (*(Line
**)b
)->icuSortKey
;
348 aVal
+= aVal
*37 + *ask
++;
351 bVal
+= bVal
*37 + *bsk
++;
357 else if (aVal
> bVal
) {
363 //---------------------------------------------------------------------------------------
365 // doKeyGen() Key Generation Timing Test
367 //---------------------------------------------------------------------------------------
376 // Adjust loop count to compensate for file size. Should be order n
377 double dLoopCount
= double(opt_loopCount
) * (1000. / double(gNumFileLines
));
378 int adj_loopCount
= int(dLoopCount
);
379 if (adj_loopCount
< 1) adj_loopCount
= 1;
382 unsigned long startTime
= timeGetTime();
385 for (loops
=0; loops
<adj_loopCount
; loops
++) {
386 for (line
=0; line
< gNumFileLines
; line
++) {
388 len
= gFileLines
[line
].len
;
390 for (iLoop
=0; iLoop
< opt_iLoopCount
; iLoop
++) {
391 t
=LCMapStringW(gWinLCID
, LCMAP_SORTKEY
,
392 gFileLines
[line
].name
, len
,
393 (unsigned short *)gFileLines
[line
].winSortKey
, 5000); // TODO something with length.
400 for (loops
=0; loops
<adj_loopCount
; loops
++) {
401 for (line
=0; line
< gNumFileLines
; line
++) {
403 len
= gFileLines
[line
].len
;
405 for (iLoop
=0; iLoop
< opt_iLoopCount
; iLoop
++) {
406 t
= ucol_getSortKey(gCol
, gFileLines
[line
].name
, len
, (unsigned char *)gFileLines
[line
].icuSortKey
, 5000);
413 for (loops
=0; loops
<adj_loopCount
; loops
++) {
414 for (line
=0; line
< gNumFileLines
; line
++) {
415 for (iLoop
=0; iLoop
< opt_iLoopCount
; iLoop
++) {
416 t
= strxfrm(gFileLines
[line
].unixSortKey
, gFileLines
[line
].unixName
, 5000);
422 unsigned long elapsedTime
= timeGetTime() - startTime
;
423 int ns
= (int)(float(1000000) * (float)elapsedTime
/ (float)(adj_loopCount
*gNumFileLines
));
425 if (opt_terse
== FALSE
) {
426 printf("Sort Key Generation: total # of keys = %d\n", loops
*gNumFileLines
);
427 printf("Sort Key Generation: time per key = %d ns\n", ns
);
435 for (line
=0; line
<gNumFileLines
; line
++) {
436 totalChars
+= u_strlen(gFileLines
[line
].name
);
438 totalKeyLen
+= strlen(gFileLines
[line
].winSortKey
);
441 totalKeyLen
+= strlen(gFileLines
[line
].icuSortKey
);
444 totalKeyLen
+= strlen(gFileLines
[line
].unixSortKey
);
448 if (opt_terse
== FALSE
) {
449 printf("Key Length / character = %f\n", (float)totalKeyLen
/ (float)totalChars
);
451 printf("%f, ", (float)totalKeyLen
/ (float)totalChars
);
457 //---------------------------------------------------------------------------------------
459 // doBinarySearch() Binary Search timing test. Each name from the list
460 // is looked up in the full sorted list of names.
462 //---------------------------------------------------------------------------------------
463 void doBinarySearch()
470 unsigned long elapsedTime
= 0;
472 // Adjust loop count to compensate for file size. Should be order n (lookups) * log n (compares/lookup)
473 // Accurate timings do not depend on this being perfect. The correction is just to try to
474 // get total running times of about the right order, so the that user doesn't need to
475 // manually adjust the loop count for every different file size.
476 double dLoopCount
= double(opt_loopCount
) * 3000. / (log10((double)gNumFileLines
) * double(gNumFileLines
));
477 if (opt_usekeys
) dLoopCount
*= 5;
478 int adj_loopCount
= int(dLoopCount
);
479 if (adj_loopCount
< 1) adj_loopCount
= 1;
482 for (;;) { // not really a loop, just allows "break" to work, to simplify
483 // inadvertantly running more than one test through here.
484 if (opt_strcmp
|| opt_strcmpCPO
)
486 unsigned long startTime
= timeGetTime();
487 typedef int32_t (U_EXPORT2
*PF
)(const UChar
*, const UChar
*);
489 if (opt_strcmpCPO
) {pf
= u_strcmpCodePointOrder
;}
490 //if (opt_strcmp && opt_win) {pf = (PF)wcscmp;} // Damn the difference between int32_t and int
491 // which forces the use of a cast here.
494 for (loops
=0; loops
<adj_loopCount
; loops
++) {
496 for (line
=0; line
< gNumFileLines
; line
++) {
497 int hi
= gNumFileLines
-1;
501 int newGuess
= (hi
+ lo
) / 2;
502 if (newGuess
== guess
)
505 for (iLoop
=0; iLoop
< opt_iLoopCount
; iLoop
++) {
506 r
= (*pf
)((gSortedLines
[line
])->name
, (gSortedLines
[guess
])->name
);
518 elapsedTime
= timeGetTime() - startTime
;
525 unsigned long startTime
= timeGetTime();
526 UCollationResult r
= UCOL_EQUAL
;
527 for (loops
=0; loops
<adj_loopCount
; loops
++) {
529 for (line
=0; line
< gNumFileLines
; line
++) {
533 lineLen
= (gSortedLines
[line
])->len
;
535 int hi
= gNumFileLines
-1;
539 int newGuess
= (hi
+ lo
) / 2;
540 if (newGuess
== guess
)
545 for (iLoop
=0; iLoop
< opt_iLoopCount
; iLoop
++) {
546 ri
= strcmp((gSortedLines
[line
])->icuSortKey
, (gSortedLines
[guess
])->icuSortKey
);
549 r
=UCOL_GREATER
; if(ri
<0) {r
=UCOL_LESS
;} else if (ri
==0) {r
=UCOL_EQUAL
;}
554 guessLen
= (gSortedLines
[guess
])->len
;
556 for (iLoop
=0; iLoop
< opt_iLoopCount
; iLoop
++) {
557 r
= ucol_strcoll(gCol
, (gSortedLines
[line
])->name
, lineLen
, (gSortedLines
[guess
])->name
, guessLen
);
570 elapsedTime
= timeGetTime() - startTime
;
576 unsigned long startTime
= timeGetTime();
578 for (loops
=0; loops
<adj_loopCount
; loops
++) {
580 for (line
=0; line
< gNumFileLines
; line
++) {
584 lineLen
= (gSortedLines
[line
])->len
;
586 int hi
= gNumFileLines
-1;
590 int newGuess
= (hi
+ lo
) / 2;
591 if (newGuess
== guess
)
595 for (iLoop
=0; iLoop
< opt_iLoopCount
; iLoop
++) {
596 r
= strcmp((gSortedLines
[line
])->winSortKey
, (gSortedLines
[guess
])->winSortKey
);
604 guessLen
= (gSortedLines
[guess
])->len
;
606 for (iLoop
=0; iLoop
< opt_iLoopCount
; iLoop
++) {
607 r
= CompareStringW(gWinLCID
, 0, (gSortedLines
[line
])->name
, lineLen
, (gSortedLines
[guess
])->name
, guessLen
);
610 if (opt_terse
== FALSE
) {
611 fprintf(stderr
, "Error returned from Windows CompareStringW.\n");
617 if (r
== 2) // strings ==
619 if (r
== 1) // line < guess
626 elapsedTime
= timeGetTime() - startTime
;
632 unsigned long startTime
= timeGetTime();
634 for (loops
=0; loops
<adj_loopCount
; loops
++) {
636 for (line
=0; line
< gNumFileLines
; line
++) {
637 int hi
= gNumFileLines
-1;
641 int newGuess
= (hi
+ lo
) / 2;
642 if (newGuess
== guess
)
646 for (iLoop
=0; iLoop
< opt_iLoopCount
; iLoop
++) {
647 r
= strcmp((gSortedLines
[line
])->unixSortKey
, (gSortedLines
[guess
])->unixSortKey
);
653 for (iLoop
=0; iLoop
< opt_iLoopCount
; iLoop
++) {
654 r
= strcoll((gSortedLines
[line
])->unixName
, (gSortedLines
[guess
])->unixName
);
658 fprintf(stderr
, "Error %d returned from strcoll.\n", errno
);
663 if (r
== 0) // strings ==
665 if (r
< 0) // line < guess
672 elapsedTime
= timeGetTime() - startTime
;
678 int ns
= (int)(float(1000000) * (float)elapsedTime
/ (float)gCount
);
679 if (opt_terse
== FALSE
) {
680 printf("binary search: total # of string compares = %d\n", gCount
);
681 printf("binary search: compares per loop = %d\n", gCount
/ loops
);
682 printf("binary search: time per compare = %d ns\n", ns
);
692 //---------------------------------------------------------------------------------------
694 // doQSort() The quick sort timing test. Uses the C library qsort function.
696 //---------------------------------------------------------------------------------------
699 Line
**sortBuf
= new Line
*[gNumFileLines
];
701 // Adjust loop count to compensate for file size. QSort should be n log(n)
702 double dLoopCount
= double(opt_loopCount
) * 3000. / (log10((double)gNumFileLines
) * double(gNumFileLines
));
703 if (opt_usekeys
) dLoopCount
*= 5;
704 int adj_loopCount
= int(dLoopCount
);
705 if (adj_loopCount
< 1) adj_loopCount
= 1;
709 unsigned long startTime
= timeGetTime();
710 if (opt_win
&& opt_usekeys
) {
711 for (i
=0; i
<opt_loopCount
; i
++) {
712 memcpy(sortBuf
, gRandomLines
, gNumFileLines
* sizeof(Line
*));
713 qsort(sortBuf
, gNumFileLines
, sizeof(Line
*), WinstrcmpK
);
717 else if (opt_win
&& opt_uselen
) {
718 for (i
=0; i
<adj_loopCount
; i
++) {
719 memcpy(sortBuf
, gRandomLines
, gNumFileLines
* sizeof(Line
*));
720 qsort(sortBuf
, gNumFileLines
, sizeof(Line
*), WinstrcmpL
);
725 else if (opt_win
&& !opt_uselen
) {
726 for (i
=0; i
<adj_loopCount
; i
++) {
727 memcpy(sortBuf
, gRandomLines
, gNumFileLines
* sizeof(Line
*));
728 qsort(sortBuf
, gNumFileLines
, sizeof(Line
*), Winstrcmp
);
732 else if (opt_icu
&& opt_usekeys
) {
733 for (i
=0; i
<adj_loopCount
; i
++) {
734 memcpy(sortBuf
, gRandomLines
, gNumFileLines
* sizeof(Line
*));
735 qsort(sortBuf
, gNumFileLines
, sizeof(Line
*), ICUstrcmpK
);
739 else if (opt_icu
&& opt_uselen
) {
740 for (i
=0; i
<adj_loopCount
; i
++) {
741 memcpy(sortBuf
, gRandomLines
, gNumFileLines
* sizeof(Line
*));
742 qsort(sortBuf
, gNumFileLines
, sizeof(Line
*), ICUstrcmpL
);
747 else if (opt_icu
&& !opt_uselen
) {
748 for (i
=0; i
<adj_loopCount
; i
++) {
749 memcpy(sortBuf
, gRandomLines
, gNumFileLines
* sizeof(Line
*));
750 qsort(sortBuf
, gNumFileLines
, sizeof(Line
*), ICUstrcmp
);
754 else if (opt_unix
&& !opt_usekeys
) {
755 for (i
=0; i
<adj_loopCount
; i
++) {
756 memcpy(sortBuf
, gRandomLines
, gNumFileLines
* sizeof(Line
*));
757 qsort(sortBuf
, gNumFileLines
, sizeof(Line
*), UNIXstrcmp
);
761 unsigned long elapsedTime
= timeGetTime() - startTime
;
762 int ns
= (int)(float(1000000) * (float)elapsedTime
/ (float)gCount
);
763 if (opt_terse
== FALSE
) {
764 printf("qsort: total # of string compares = %d\n", gCount
);
765 printf("qsort: time per compare = %d ns\n", ns
);
773 //---------------------------------------------------------------------------------------
775 // doKeyHist() Output a table of data for
776 // average sort key size vs. string length.
778 //---------------------------------------------------------------------------------------
783 // Find the maximum string length
784 for (i
=0; i
<gNumFileLines
; i
++) {
785 if (gFileLines
[i
].len
> maxLen
) maxLen
= gFileLines
[i
].len
;
788 // Allocate arrays to hold the histogram data
789 int *accumulatedLen
= new int[maxLen
+1];
790 int *numKeysOfSize
= new int[maxLen
+1];
791 for (i
=0; i
<=maxLen
; i
++) {
792 accumulatedLen
[i
] = 0;
793 numKeysOfSize
[i
] = 0;
796 // Fill the arrays...
797 for (i
=0; i
<gNumFileLines
; i
++) {
798 int len
= gFileLines
[i
].len
;
799 accumulatedLen
[len
] += strlen(gFileLines
[i
].icuSortKey
);
800 numKeysOfSize
[len
] += 1;
803 // And write out averages
804 printf("String Length, Avg Key Length, Avg Key Len per char\n");
805 for (i
=1; i
<=maxLen
; i
++) {
806 if (numKeysOfSize
[i
] > 0) {
807 printf("%d, %f, %f\n", i
, (float)accumulatedLen
[i
] / (float)numKeysOfSize
[i
],
808 (float)accumulatedLen
[i
] / (float)(numKeysOfSize
[i
] * i
));
811 delete []accumulatedLen
;
812 delete []numKeysOfSize
;
815 //---------------------------------------------------------------------------------------
817 // doForwardIterTest(UBool) Forward iteration test
818 // argument null-terminated string used
820 //---------------------------------------------------------------------------------------
821 void doForwardIterTest(UBool haslen
) {
824 UErrorCode error
= U_ZERO_ERROR
;
825 printf("\n\nPerforming forward iteration performance test with ");
828 printf("non-null terminated data -----------\n");
831 printf("null terminated data -----------\n");
833 printf("performance test on strings from file -----------\n");
835 UChar dummytext
[] = {0, 0};
836 UCollationElements
*iter
= ucol_openElements(gCol
, NULL
, 0, &error
);
837 ucol_setText(iter
, dummytext
, 1, &error
);
840 unsigned long startTime
= timeGetTime();
841 while (count
< opt_loopCount
) {
843 while (linecount
< gNumFileLines
) {
844 UChar
*str
= gFileLines
[linecount
].name
;
845 int strlen
= haslen
?gFileLines
[linecount
].len
:-1;
846 ucol_setText(iter
, str
, strlen
, &error
);
847 while (ucol_next(iter
, &error
) != UCOL_NULLORDER
) {
855 unsigned long elapsedTime
= timeGetTime() - startTime
;
856 printf("elapsedTime %ld\n", elapsedTime
);
858 // empty loop recalculation
860 startTime
= timeGetTime();
861 while (count
< opt_loopCount
) {
863 while (linecount
< gNumFileLines
) {
864 UChar
*str
= gFileLines
[linecount
].name
;
865 int strlen
= haslen
?gFileLines
[linecount
].len
:-1;
866 ucol_setText(iter
, str
, strlen
, &error
);
871 elapsedTime
-= (timeGetTime() - startTime
);
872 printf("elapsedTime %ld\n", elapsedTime
);
874 ucol_closeElements(iter
);
876 int ns
= (int)(float(1000000) * (float)elapsedTime
/ (float)gCount
);
877 printf("Total number of strings compared %d in %d loops\n", gNumFileLines
,
879 printf("Average time per ucol_next() nano seconds %d\n", ns
);
881 printf("performance test on skipped-5 concatenated strings from file -----------\n");
885 // appending all the strings
887 while (linecount
< gNumFileLines
) {
888 strlen
+= haslen
?gFileLines
[linecount
].len
:
889 u_strlen(gFileLines
[linecount
].name
);
892 str
= (UChar
*)malloc(sizeof(UChar
) * strlen
);
895 while (strindex
< strlen
) {
897 len
+= haslen
?gFileLines
[linecount
].len
:
898 u_strlen(gFileLines
[linecount
].name
);
899 memcpy(str
+ strindex
, gFileLines
[linecount
].name
,
900 sizeof(UChar
) * len
);
905 printf("Total size of strings %d\n", strlen
);
913 iter
= ucol_openElements(gCol
, str
, strlen
, &error
);
915 strlen
= u_strlen(str
);
917 strlen
-= 5; // any left over characters are not iterated,
918 // this is to ensure the backwards and forwards iterators
919 // gets the same position
920 startTime
= timeGetTime();
921 while (count
< opt_loopCount
) {
924 ucol_setOffset(iter
, strindex
, &error
);
926 if (ucol_next(iter
, &error
) == UCOL_NULLORDER
) {
933 if (strindex
> strlen
) {
936 ucol_setOffset(iter
, strindex
, &error
);
943 elapsedTime
= timeGetTime() - startTime
;
944 printf("elapsedTime %ld\n", elapsedTime
);
946 // empty loop recalculation
949 startTime
= timeGetTime();
950 while (count
< opt_loopCount
) {
953 ucol_setOffset(iter
, strindex
, &error
);
959 if (strindex
> strlen
) {
962 ucol_setOffset(iter
, strindex
, &error
);
968 elapsedTime
-= (timeGetTime() - startTime
);
969 printf("elapsedTime %ld\n", elapsedTime
);
971 ucol_closeElements(iter
);
973 printf("gCount %d\n", gCount
);
974 ns
= (int)(float(1000000) * (float)elapsedTime
/ (float)gCount
);
975 printf("Average time per ucol_next() nano seconds %d\n", ns
);
978 //---------------------------------------------------------------------------------------
980 // doBackwardIterTest(UBool) Backwards iteration test
981 // argument null-terminated string used
983 //---------------------------------------------------------------------------------------
984 void doBackwardIterTest(UBool haslen
) {
986 UErrorCode error
= U_ZERO_ERROR
;
987 printf("\n\nPerforming backward iteration performance test with ");
990 printf("non-null terminated data -----------\n");
993 printf("null terminated data -----------\n");
996 printf("performance test on strings from file -----------\n");
998 UCollationElements
*iter
= ucol_openElements(gCol
, NULL
, 0, &error
);
999 UChar dummytext
[] = {0, 0};
1000 ucol_setText(iter
, dummytext
, 1, &error
);
1003 unsigned long startTime
= timeGetTime();
1004 while (count
< opt_loopCount
) {
1006 while (linecount
< gNumFileLines
) {
1007 UChar
*str
= gFileLines
[linecount
].name
;
1008 int strlen
= haslen
?gFileLines
[linecount
].len
:-1;
1009 ucol_setText(iter
, str
, strlen
, &error
);
1010 while (ucol_previous(iter
, &error
) != UCOL_NULLORDER
) {
1018 unsigned long elapsedTime
= timeGetTime() - startTime
;
1020 printf("elapsedTime %ld\n", elapsedTime
);
1022 // empty loop recalculation
1024 startTime
= timeGetTime();
1025 while (count
< opt_loopCount
) {
1027 while (linecount
< gNumFileLines
) {
1028 UChar
*str
= gFileLines
[linecount
].name
;
1029 int strlen
= haslen
?gFileLines
[linecount
].len
:-1;
1030 ucol_setText(iter
, str
, strlen
, &error
);
1035 elapsedTime
-= (timeGetTime() - startTime
);
1037 printf("elapsedTime %ld\n", elapsedTime
);
1038 ucol_closeElements(iter
);
1040 int ns
= (int)(float(1000000) * (float)elapsedTime
/ (float)gCount
);
1041 printf("Total number of strings compared %d in %d loops\n", gNumFileLines
,
1043 printf("Average time per ucol_previous() nano seconds %d\n", ns
);
1045 printf("performance test on skipped-5 concatenated strings from file -----------\n");
1049 // appending all the strings
1051 while (linecount
< gNumFileLines
) {
1052 strlen
+= haslen
?gFileLines
[linecount
].len
:
1053 u_strlen(gFileLines
[linecount
].name
);
1056 str
= (UChar
*)malloc(sizeof(UChar
) * strlen
);
1059 while (strindex
< strlen
) {
1061 len
+= haslen
?gFileLines
[linecount
].len
:
1062 u_strlen(gFileLines
[linecount
].name
);
1063 memcpy(str
+ strindex
, gFileLines
[linecount
].name
,
1064 sizeof(UChar
) * len
);
1069 printf("Total size of strings %d\n", strlen
);
1078 iter
= ucol_openElements(gCol
, str
, strlen
, &error
);
1080 strlen
= u_strlen(str
);
1083 startTime
= timeGetTime();
1084 while (count
< opt_loopCount
) {
1087 ucol_setOffset(iter
, strindex
, &error
);
1089 if (ucol_previous(iter
, &error
) == UCOL_NULLORDER
) {
1096 if (strindex
> strlen
) {
1099 ucol_setOffset(iter
, strindex
, &error
);
1106 elapsedTime
= timeGetTime() - startTime
;
1107 printf("elapsedTime %ld\n", elapsedTime
);
1109 // empty loop recalculation
1112 startTime
= timeGetTime();
1113 while (count
< opt_loopCount
) {
1116 ucol_setOffset(iter
, strindex
, &error
);
1122 if (strindex
> strlen
) {
1125 ucol_setOffset(iter
, strindex
, &error
);
1131 elapsedTime
-= (timeGetTime() - startTime
);
1132 printf("elapsedTime %ld\n", elapsedTime
);
1133 ucol_closeElements(iter
);
1135 printf("gCount %d\n", gCount
);
1136 ns
= (int)(float(1000000) * (float)elapsedTime
/ (float)gCount
);
1137 printf("Average time per ucol_previous() nano seconds %d\n", ns
);
1140 //---------------------------------------------------------------------------------------
1142 // doIterTest() Iteration test
1144 //---------------------------------------------------------------------------------------
1146 doForwardIterTest(opt_uselen
);
1147 doBackwardIterTest(opt_uselen
);
1151 //----------------------------------------------------------------------------------------
1153 // UnixConvert -- Convert the lines of the file to the encoding for UNIX
1154 // Since it appears that Unicode support is going in the general
1155 // direction of the use of UTF-8 locales, that is the approach
1156 // that is used here.
1158 //----------------------------------------------------------------------------------------
1159 void UnixConvert() {
1162 UConverter
*cvrtr
; // An ICU code page converter.
1163 UErrorCode status
= U_ZERO_ERROR
;
1166 cvrtr
= ucnv_open("utf-8", &status
); // we are just doing UTF-8 locales for now.
1167 if (U_FAILURE(status
)) {
1168 fprintf(stderr
, "ICU Converter open failed.: %s\n", u_errorName(status
));
1172 for (line
=0; line
< gNumFileLines
; line
++) {
1173 int sizeNeeded
= ucnv_fromUChars(cvrtr
,
1174 0, // ptr to target buffer.
1175 0, // length of target buffer.
1176 gFileLines
[line
].name
,
1177 -1, // source is null terminated
1179 if (status
!= U_BUFFER_OVERFLOW_ERROR
&& status
!= U_ZERO_ERROR
) {
1180 //fprintf(stderr, "Conversion from Unicode, something is wrong.\n");
1183 status
= U_ZERO_ERROR
;
1184 gFileLines
[line
].unixName
= new char[sizeNeeded
+1];
1185 sizeNeeded
= ucnv_fromUChars(cvrtr
,
1186 gFileLines
[line
].unixName
, // ptr to target buffer.
1187 sizeNeeded
+1, // length of target buffer.
1188 gFileLines
[line
].name
,
1189 -1, // source is null terminated
1191 if (U_FAILURE(status
)) {
1192 fprintf(stderr
, "ICU Conversion Failed.: %d\n", status
);
1195 gFileLines
[line
].unixName
[sizeNeeded
] = 0;
1201 //----------------------------------------------------------------------------------------
1203 // class UCharFile Class to hide all the gorp to read a file in
1204 // and produce a stream of UChars.
1206 //----------------------------------------------------------------------------------------
1209 UCharFile(const char *fileName
);
1212 UBool
eof() {return fEof
;};
1213 UBool
error() {return fError
;};
1216 UCharFile (const UCharFile
& /*other*/) {}; // No copy constructor.
1217 UCharFile
& operator = (const UCharFile
&/*other*/) {return *this;}; // No assignment op
1223 UChar fPending2ndSurrogate
;
1225 enum {UTF16LE
, UTF16BE
, UTF8
} fEncoding
;
1228 UCharFile::UCharFile(const char * fileName
) {
1232 fFile
= fopen(fName
, "rb");
1233 fPending2ndSurrogate
= 0;
1234 if (fFile
== NULL
) {
1235 fprintf(stderr
, "Can not open file \"%s\"\n", opt_fName
);
1240 // Look for the byte order mark at the start of the file.
1242 int BOMC1
, BOMC2
, BOMC3
;
1243 BOMC1
= fgetc(fFile
);
1244 BOMC2
= fgetc(fFile
);
1246 if (BOMC1
== 0xff && BOMC2
== 0xfe) {
1247 fEncoding
= UTF16LE
; }
1248 else if (BOMC1
== 0xfe && BOMC2
== 0xff) {
1249 fEncoding
= UTF16BE
; }
1250 else if (BOMC1
== 0xEF && BOMC2
== 0xBB && (BOMC3
= fgetc(fFile
)) == 0xBF ) {
1254 fprintf(stderr
, "collperf: file \"%s\" encoding must be UTF-8 or UTF-16, and "
1255 "must include a BOM.\n", fileName
);
1262 UCharFile::~UCharFile() {
1268 UChar
UCharFile::get() {
1270 switch (fEncoding
) {
1297 if (fPending2ndSurrogate
!= 0) {
1298 c
= fPending2ndSurrogate
;
1299 fPending2ndSurrogate
= 0;
1303 int ch
= fgetc(fFile
); // Note: c and ch are separate cause eof test doesn't work on UChar type.
1311 // It's ascii. No further utf-8 conversion.
1316 // Figure out the lenght of the char and read the rest of the bytes
1317 // into a temp array.
1319 if (ch
>= 0xF0) {nBytes
=4;}
1320 else if (ch
>= 0xE0) {nBytes
=3;}
1321 else if (ch
>= 0xC0) {nBytes
=2;}
1323 fprintf(stderr
, "utf-8 encoded file contains corrupt data.\n");
1328 unsigned char bytes
[10];
1329 bytes
[0] = (unsigned char)ch
;
1331 for (i
=1; i
<nBytes
; i
++) {
1332 bytes
[i
] = fgetc(fFile
);
1333 if (bytes
[i
] < 0x80 || bytes
[i
] >= 0xc0) {
1334 fprintf(stderr
, "utf-8 encoded file contains corrupt data.\n");
1340 // Convert the bytes from the temp array to a Unicode char.
1343 UTF8_NEXT_CHAR_UNSAFE(bytes
, i
, cp
);
1346 if (cp
>= 0x10000) {
1347 // The code point needs to be broken up into a utf-16 surrogate pair.
1348 // Process first half this time through the main loop, and
1349 // remember the other half for the next time through.
1352 UTF16_APPEND_CHAR_UNSAFE(utf16Buf
, i
, cp
);
1353 fPending2ndSurrogate
= utf16Buf
[1];
1359 c
= 0xFFFD; /* Error, unspecified codepage*/
1360 fprintf(stderr
, "UCharFile: Error: unknown fEncoding\n");
1366 //----------------------------------------------------------------------------------------
1368 // openRulesCollator - Command line specified a rules file. Read it in
1369 // and open a collator with it.
1371 //----------------------------------------------------------------------------------------
1372 UCollator
*openRulesCollator() {
1373 UCharFile
f(opt_rules
);
1379 UChar
*buf
= (UChar
*)malloc(bufLen
* sizeof(UChar
));
1395 buf
= (UChar
*)realloc(buf
, bufLen
);
1404 UErrorCode status
= U_ZERO_ERROR
;
1405 UCollator
*coll
= ucol_openRules(buf
, u_strlen(buf
), UCOL_OFF
,
1406 UCOL_DEFAULT_STRENGTH
, NULL
, &status
);
1407 if (U_FAILURE(status
)) {
1408 fprintf(stderr
, "ICU ucol_openRules() open failed.: %d\n", status
);
1419 //----------------------------------------------------------------------------------------
1421 // Main -- process command line, read in and pre-process the test file,
1422 // call other functions to do the actual tests.
1424 //----------------------------------------------------------------------------------------
1425 int main(int argc
, const char** argv
) {
1426 if (ProcessOptions(argc
, argv
, opts
) != TRUE
|| opt_help
|| opt_fName
== 0) {
1427 printf(gUsageString
);
1431 // Make sure that we've only got one API selected.
1432 if (opt_unix
|| opt_win
) opt_icu
= FALSE
;
1433 if (opt_unix
) opt_win
= FALSE
;
1436 // Set up an ICU collator
1438 UErrorCode status
= U_ZERO_ERROR
;
1440 if (opt_rules
!= 0) {
1441 gCol
= openRulesCollator();
1442 if (gCol
== 0) {return -1;}
1445 gCol
= ucol_open(opt_locale
, &status
);
1446 if (U_FAILURE(status
)) {
1447 fprintf(stderr
, "Collator creation failed.: %d\n", status
);
1451 if (status
==U_USING_DEFAULT_WARNING
&& opt_terse
==FALSE
) {
1452 fprintf(stderr
, "Warning, U_USING_DEFAULT_WARNING for %s\n", opt_locale
);
1454 if (status
==U_USING_FALLBACK_WARNING
&& opt_terse
==FALSE
) {
1455 fprintf(stderr
, "Warning, U_USING_FALLBACK_ERROR for %s\n", opt_locale
);
1459 ucol_setAttribute(gCol
, UCOL_NORMALIZATION_MODE
, UCOL_ON
, &status
);
1461 if (opt_french
&& opt_frenchoff
) {
1462 fprintf(stderr
, "collperf: Error, specified both -french and -frenchoff options.");
1466 ucol_setAttribute(gCol
, UCOL_FRENCH_COLLATION
, UCOL_ON
, &status
);
1468 if (opt_frenchoff
) {
1469 ucol_setAttribute(gCol
, UCOL_FRENCH_COLLATION
, UCOL_OFF
, &status
);
1472 ucol_setAttribute(gCol
, UCOL_CASE_FIRST
, UCOL_LOWER_FIRST
, &status
);
1475 ucol_setAttribute(gCol
, UCOL_CASE_FIRST
, UCOL_UPPER_FIRST
, &status
);
1478 ucol_setAttribute(gCol
, UCOL_CASE_LEVEL
, UCOL_ON
, &status
);
1481 ucol_setAttribute(gCol
, UCOL_ALTERNATE_HANDLING
, UCOL_SHIFTED
, &status
);
1483 if (opt_level
!= 0) {
1484 switch (opt_level
) {
1486 ucol_setAttribute(gCol
, UCOL_STRENGTH
, UCOL_PRIMARY
, &status
);
1489 ucol_setAttribute(gCol
, UCOL_STRENGTH
, UCOL_SECONDARY
, &status
);
1492 ucol_setAttribute(gCol
, UCOL_STRENGTH
, UCOL_TERTIARY
, &status
);
1495 ucol_setAttribute(gCol
, UCOL_STRENGTH
, UCOL_QUATERNARY
, &status
);
1498 ucol_setAttribute(gCol
, UCOL_STRENGTH
, UCOL_IDENTICAL
, &status
);
1501 fprintf(stderr
, "-level param must be between 1 and 5\n");
1506 if (U_FAILURE(status
)) {
1507 fprintf(stderr
, "Collator attribute setting failed.: %d\n", status
);
1513 // Set up a Windows LCID
1515 if (opt_langid
!= 0) {
1516 gWinLCID
= MAKELCID(opt_langid
, SORT_DEFAULT
);
1519 gWinLCID
= uloc_getLCID(opt_locale
);
1524 // Set the UNIX locale
1527 if (setlocale(LC_ALL
, opt_locale
) == 0) {
1528 fprintf(stderr
, "setlocale(LC_ALL, %s) failed.\n", opt_locale
);
1533 // Read in the input file.
1534 // File assumed to be utf-16.
1535 // Lines go onto heap buffers. Global index array to line starts is created.
1536 // Lines themselves are null terminated.
1539 UCharFile
f(opt_fName
);
1544 const int MAXLINES
= 100000;
1545 gFileLines
= new Line
[MAXLINES
];
1549 // Read the file, split into lines, and save in memory.
1550 // Loop runs once per utf-16 value from the input file,
1551 // (The number of bytes read from file per loop iteration depends on external encoding.)
1560 // We now have a good UTF-16 value in c.
1562 // Watch for CR, LF, EOF; these finish off a line.
1567 if (f
.eof() || c
== 0x0a || c
==0x2028) { // Unipad inserts 2028 line separators!
1570 gFileLines
[gNumFileLines
].name
= new UChar
[column
];
1571 gFileLines
[gNumFileLines
].len
= column
-1;
1572 memcpy(gFileLines
[gNumFileLines
].name
, buf
, column
* sizeof(UChar
));
1575 if (gNumFileLines
>= MAXLINES
) {
1576 fprintf(stderr
, "File too big. Max number of lines is %d\n", MAXLINES
);
1581 if (c
== 0xa || c
== 0x2028)
1589 static UBool warnFlag
= TRUE
;
1591 fprintf(stderr
, "Warning - file line longer than 1023 chars truncated.\n");
1598 if (opt_terse
== FALSE
) {
1599 printf("file \"%s\", %d lines.\n", opt_fName
, gNumFileLines
);
1603 // Convert the lines to the UNIX encoding.
1609 // Pre-compute ICU sort keys for the lines of the file.
1614 for (line
=0; line
<gNumFileLines
; line
++) {
1615 t
= ucol_getSortKey(gCol
, gFileLines
[line
].name
, -1, (unsigned char *)buf
, sizeof(buf
));
1616 gFileLines
[line
].icuSortKey
= new char[t
];
1618 if (t
> (int32_t)sizeof(buf
)) {
1619 t
= ucol_getSortKey(gCol
, gFileLines
[line
].name
, -1, (unsigned char *)gFileLines
[line
].icuSortKey
, t
);
1623 memcpy(gFileLines
[line
].icuSortKey
, buf
, t
);
1630 // Pre-compute Windows sort keys for the lines of the file.
1632 for (line
=0; line
<gNumFileLines
; line
++) {
1633 t
=LCMapStringW(gWinLCID
, LCMAP_SORTKEY
, gFileLines
[line
].name
, -1, buf
, sizeof(buf
));
1634 gFileLines
[line
].winSortKey
= new char[t
];
1635 if (t
> (int32_t)sizeof(buf
)) {
1636 t
= LCMapStringW(gWinLCID
, LCMAP_SORTKEY
, gFileLines
[line
].name
, -1, (unsigned short *)(gFileLines
[line
].winSortKey
), t
);
1640 memcpy(gFileLines
[line
].winSortKey
, buf
, t
);
1645 // Pre-compute UNIX sort keys for the lines of the file.
1648 for (line
=0; line
<gNumFileLines
; line
++) {
1649 t
=strxfrm((char *)buf
, gFileLines
[line
].unixName
, sizeof(buf
));
1650 gFileLines
[line
].unixSortKey
= new char[t
];
1651 if (t
> (int32_t)sizeof(buf
)) {
1652 t
= strxfrm(gFileLines
[line
].unixSortKey
, gFileLines
[line
].unixName
, sizeof(buf
));
1656 memcpy(gFileLines
[line
].unixSortKey
, buf
, t
);
1663 // Dump file lines, CEs, Sort Keys if requested.
1667 for (line
=0; line
<gNumFileLines
; line
++) {
1669 UChar c
= gFileLines
[line
].name
[i
];
1672 if (c
< 0x20 || c
> 0x7e) {
1673 printf("\\u%.4x", c
);
1682 UCollationElements
*CEiter
= ucol_openElements(gCol
, gFileLines
[line
].name
, -1, &status
);
1686 ce
= ucol_next(CEiter
, &status
);
1687 if (ce
== UCOL_NULLORDER
) {
1690 printf(" %.8x", ce
);
1697 ucol_closeElements(CEiter
);
1700 printf(" ICU Sort Key: ");
1702 unsigned char c
= gFileLines
[line
].icuSortKey
[i
];
1707 if (i
> 0 && i
% 20 == 0) {
1717 // Pre-sort the lines.
1720 gSortedLines
= new Line
*[gNumFileLines
];
1721 for (i
=0; i
<gNumFileLines
; i
++) {
1722 gSortedLines
[i
] = &gFileLines
[i
];
1726 qsort(gSortedLines
, gNumFileLines
, sizeof(Line
*), Winstrcmp
);
1728 else if (opt_unix
) {
1729 qsort(gSortedLines
, gNumFileLines
, sizeof(Line
*), UNIXstrcmp
);
1733 qsort(gSortedLines
, gNumFileLines
, sizeof(Line
*), ICUstrcmp
);
1738 // Make up a randomized order, will be used for sorting tests.
1740 gRandomLines
= new Line
*[gNumFileLines
];
1741 for (i
=0; i
<gNumFileLines
; i
++) {
1742 gRandomLines
[i
] = &gFileLines
[i
];
1744 qsort(gRandomLines
, gNumFileLines
, sizeof(Line
*), ICURandomCmp
);
1750 // We've got the file read into memory. Go do something with it.
1753 if (opt_qsort
) doQSort();
1754 if (opt_binsearch
) doBinarySearch();
1755 if (opt_keygen
) doKeyGen();
1756 if (opt_keyhist
) doKeyHist();
1757 if (opt_itertest
) doIterTest();