Home | History | Annotate | Download | only in bench
      1 /*
      2  * Copyright 2018 Google Inc.
      3  *
      4  * Use of this source code is governed by a BSD-style license that can be
      5  * found in the LICENSE file.
      6  */
      7 
      8 #include <vector>
      9 
     10 #include "Benchmark.h"
     11 #include "SkFontTypes.h"
     12 #include "SkMakeUnique.h"
     13 #include "SkTypeface.h"
     14 #include "SkUTF.h"
     15 #include "SkUtils.h"
     16 
     17 // From Project Guttenberg. This is UTF-8 text.
     18 static const char* atext[] = {
     19         "Call me Ishmael.  Some years ago--never mind how",
     20         "long precisely --having little or no money in my purse, and nothing particular",
     21         "to interest me on shore, I thought I would sail about a little and see the",
     22         "watery part of the world.  It is a way I have of driving off the spleen, and",
     23         "regulating the circulation.  Whenever I find myself growing grim about the",
     24         "mouth; whenever it is a damp, drizzly November in my soul; whenever I find",
     25         "myself involuntarily pausing before coffin warehouses, and bringing up the",
     26         "rear of every funeral I meet; and especially whenever my hypos get such an",
     27         "upper hand of me, that it requires a strong moral principle to prevent me",
     28         "from deliberately stepping into the street, and methodically knocking",
     29         "people's hats off--then, I account it high time to get to sea as soon as I can.",
     30         "",
     31         "This is my substitute for pistol and ball.  With a philosophical flourish",
     32         "Cato throws himself upon his sword; I quietly take to the ship.  There is",
     33         "nothing surprising in this.  If they but knew it, almost all men in their",
     34         "degree, some time or other, cherish very nearly the same feelings towards the",
     35         "ocean with me.  There now is your insular city of the Manhattoes, belted round",
     36         "by wharves as Indian isles by coral reefs--commerce surrounds it with her surf.",
     37         "",
     38         "Right and left, the streets take you waterward.  Its extreme down-town is",
     39         "the battery, where that noble mole is washed by waves, and cooled by",
     40         "breezes, which a few hours previous were out of sight of land.  Look at the",
     41         "crowds of water-gazers there.  Circumambulate the city of a dreamy Sabbath",
     42         "afternoon.  Go from Corlears Hook to Coenties Slip, and from thence, by",
     43         "Whitehall northward.  What do you see?--Posted like silent sentinels all",
     44         "around the town, stand thousands upon thousands of mortal men fixed in ocean",
     45         "reveries.  Some leaning against the spiles; some seated upon the pier-heads;",
     46         "some looking over the bulwarks glasses!",
     47         "of ships from China; some high aloft in the rigging, as if striving to get a",
     48         "still better seaward peep.  But these are all landsmen; of week days pent up",
     49         "in lath and plaster--tied to counters, nailed to benches, clinched to desks.",
     50         "How then is this?  Are the green fields gone?  What do they here?  But look!",
     51         "here come more crowds, pacing straight for the water, and seemingly bound for",
     52         "a dive.  Strange!  Nothing will content them but the extremest limit of the",
     53         "land; loitering under the shady lee of yonder warehouses will not suffice.",
     54         "No.  They must get just as nigh the water as they possibly can without falling",
     55         "in.  And there they stand--miles of them--leagues.  Inlanders all, they come",
     56         "from lanes and alleys, streets and avenues, --north, east, south, and west.",
     57         "Yet here they all unite.  Tell me, does the magnetic virtue of the needles of",
     58         "the compasses of all those ships attract them thither?  Once more.  Say, you",
     59         "are in the country; in some high land of lakes.  Take almost any path you",
     60         "please, and ten to one it carries you down in a dale, and leaves you there",
     61         "by a pool in the stream.  There is magic in it.  Let the most absent-minded",
     62         "of men be plunged in his deepest reveries--stand that man on his legs, set his",
     63         "feet a-going, and he will infallibly lead you to water, if water there be in",
     64         "all that region.  Should you ever be athirst in the great American desert,",
     65         "try this experiment, if your caravan happen to be supplied with a metaphysical",
     66         "professor.  Yes, as every one knows, meditation and water are wedded for ever.",
     67         "",
     68         "But here is an artist.  He desires to paint you the dreamiest, shadiest,",
     69         "quietest, most enchanting bit of romantic landscape in all the valley of the",
     70         "Saco.  What is the chief element he employs?  There stand his trees, each with",
     71         "a hollow trunk, as if a hermit and a crucifix were within; and here sleeps",
     72         "his meadow, and there sleep his cattle; and up from yonder cottage goes a",
     73         "sleepy smoke.  Deep into distant woodlands winds a mazy way, reaching to",
     74         "overlapping spurs of mountains bathed in their hill-side blue.  But though",
     75         "the picture lies thus tranced, and though this pine-tree shakes down its sighs",
     76         "like leaves upon this shepherd's head, yet all were vain, unless the",
     77         "shepherd's eye were fixed upon the magic stream before him.  Go visit the",
     78         "Prairies in June,",
     79         "",
     80         "when for scores on scores of miles you wade knee-deep among Tiger-lilies--what",
     81         "is the one charm wanting? --Water --there is not a drop of water there!  Were",
     82         "Niagara but a cataract of sand, would you travel your thousand miles to see",
     83         "it?  Why did the poor poet of Tennessee, upon suddenly receiving two handfuls",
     84         "of silver, deliberate whether to buy him a coat, which he sadly needed, or",
     85         "invest his money in a pedestrian trip to Rockaway Beach?  Why is almost every",
     86         "robust healthy boy with a robust healthy soul in him, at some time or other",
     87         "crazy to go to sea?  Why upon your first voyage as a passenger, did you",
     88         "yourself feel such a mystical vibration, when first told that you and your",
     89         "ship were now out of sight of land?  Why did the old Persians hold the sea",
     90         "holy?  Why did the Greeks give it a separate deity, and own brother of Jove?",
     91         "Surely all this is not without meaning.  And still deeper the meaning of that",
     92         "story of Narcissus, who because he could not grasp the tormenting, mild image",
     93         "he saw in the fountain, plunged into it and was drowned.  But that same",
     94         "image, we ourselves see in all rivers and oceans.  It is the image of the",
     95         "ungraspable phantom of life; and this is the key to it all.  Now, when I say",
     96         "that I am in the habit of going to sea whenever I begin to grow hazy about the",
     97         "eyes, and begin to be over conscious of my lungs, I do not mean to have it",
     98         "inferred that I ever go to sea as a passenger.  For to go as a passenger you",
     99         "must needs have a purse, and a purse is but a rag unless you have something",
    100         "in it.  Besides, passengers get sea-sick --grow quarrelsome --don't sleep of",
    101         "nights --do not enjoy themselves much, as a general thing; --no, I never go as a",
    102         "passenger; nor, though I am something of a salt, do I ever go to sea as a",
    103         "Commodore, or a Captain, or a Cook.  I abandon the glory and distinction of",
    104         "such offices to those who like them.  For my part, I abominate all honorable",
    105         "respectable toils, trials, and tribulations of every kind whatsoever.  It is",
    106         "quite as much as I can do to take care of myself, without taking care of",
    107         "ships, barques, brigs, schooners, and what not.  And as for going as cook, --",
    108         "though I confess there is considerable glory in that, a cook being a sort of",
    109         "officer on ship-board --yet, somehow, I never fancied broiling fowls; --though",
    110         "once broiled, judiciously buttered, and judgmatically salted and peppered,",
    111         "there is no one who will",
    112         "",
    113         "speak more respectfully, not to say reverentially, of a broiled fowl than I",
    114         "will.  It is out of the idolatrous dotings of the old Egyptians upon broiled",
    115         "ibis and roasted river horse, that you see the mummies of those creatures in",
    116         "their huge bake-houses the pyramids.  No, when I go to sea, I go as a simple",
    117         "sailor, right before the mast, plumb down into the forecastle, aloft there",
    118         "to the royal mast-head.  True, they rather order me about some, and make me",
    119         "jump from spar to spar, like a grasshopper in a May meadow.  And at first,",
    120         "this sort of thing is unpleasant enough.  It touches one's sense of honor,",
    121         "particularly if you come of an old established family in the land, the van",
    122         "Rensselaers, or Randolphs, or Hardicanutes.  And more than all, if just",
    123         "previous to putting your hand into the tar-pot, you have been lording it as a",
    124         "country schoolmaster, making the tallest boys stand in awe of you.  The",
    125         "transition is a keen one, I assure you, from the schoolmaster to a sailor,",
    126         "and requires a strong decoction of Seneca and the Stoics to enable you to grin",
    127         "and bear it.  But even this wears off in time.  What of it, if some old hunks",
    128         "of a sea-captain orders me to get a broom and sweep down the decks?  What does",
    129         "that indignity amount to, weighed, I mean, in the scales of the New",
    130         "Testament?  Do you think the archangel Gabriel thinks anything the less of me,",
    131         "because I promptly and respectfully obey that old hunks in that particular",
    132         "instance?  Who aint a slave?  Tell me that.  Well, then, however the old",
    133         "sea-captains may order me about--however they may thump and punch me about, I",
    134         "have the satisfaction of knowing that it is all right; that everybody else",
    135         "is one way or other served in much the same way -- either in a physical or",
    136         "metaphysical point of view, that is; and so the universal thump is passed",
    137         "round, and all hands should rub each other's shoulder-blades, and be",
    138         "content.  Again, I always go to sea as a sailor, because they make a point of",
    139         "paying me for my trouble, whereas they never pay passengers a single penny",
    140         "that I ever heard of.  On the contrary, passengers themselves must pay.  And",
    141         "there is all the difference in the world between paying and being paid.  The",
    142         "act of paying is perhaps the most uncomfortable infliction that the two",
    143         "orchard thieves entailed upon us."
    144 };
    145 
    146 static const char* ctext[] = {
    147         "",
    148         "",
    149         "",
    150         "",
    151         "",
    152         "",
    153         "",
    154         "",
    155         "",
    156         "",
    157         "",
    158         "",
    159         "",
    160         "",
    161         "",
    162         "",
    163         "",
    164         "",
    165         "",
    166         "",
    167         "",
    168         "",
    169         "",
    170         "",
    171         "",
    172         "",
    173         "",
    174         "",
    175         "",
    176         "",
    177         "",
    178         "",
    179         "",
    180         "",
    181         "",
    182         "",
    183         "",
    184         "",
    185         "",
    186         "",
    187         "",
    188         "",
    189         "",
    190         "",
    191         "",
    192         "",
    193         "",
    194         "",
    195         "",
    196         "",
    197         "",
    198         "",
    199         "",
    200         "",
    201         "",
    202         "",
    203         "",
    204         "",
    205         "",
    206         "",
    207         "",
    208         "",
    209         "",
    210         ""};
    211 
    212 
    213 class UtfToGlyph : public Benchmark {
    214 public:
    215     UtfToGlyph(SkTextEncoding encoding, const char* (*text), int lineCount, const char* name)
    216         : fEncoding{encoding}
    217         , fText{text}
    218         , fLineCount{lineCount}
    219         , fName{name} { }
    220 
    221 protected:
    222     const char* onGetName() override {
    223         return fName;
    224     }
    225 
    226     bool isSuitableFor(Backend backend) override {
    227         return backend == kNonRendering_Backend;
    228     }
    229 
    230     void onDelayedSetup() override {
    231         int maxGlyphs = 0;
    232         for (int i = 0; i < fLineCount; i++) {
    233             fLines.emplace_back(this->convertLine(i));
    234             maxGlyphs = std::max(maxGlyphs, fLines.back()->glyphCount);
    235         }
    236         fGlyphIds.insert(fGlyphIds.begin(), maxGlyphs, 0);
    237         fTypeface = SkTypeface::MakeFromName("monospace", SkFontStyle());
    238     }
    239 
    240     void onDraw(int loops, SkCanvas* canvas) override {
    241         // Do more loops to reduce variance.
    242         for (int i = 0; i < loops * 3; ++i) {
    243             for (auto& line : fLines) {
    244                 fTypeface->charsToGlyphs(line->utf.data(),
    245                                   (SkTypeface::Encoding)fEncoding, fGlyphIds.data(),
    246                                   line->glyphCount);
    247             }
    248         }
    249     }
    250 
    251 private:
    252     struct Line {
    253         int glyphCount = 0;
    254         std::vector<char> utf;
    255     };
    256 
    257     std::unique_ptr<Line> convertLine(int lineIndex) {
    258         std::unique_ptr<Line> result = skstd::make_unique<Line>();
    259 
    260         const char* cursor = fText[lineIndex];
    261         size_t len = strlen(cursor);
    262         const char* end = cursor + len;
    263         result->glyphCount = SkUTF::CountUTF8(cursor, len);
    264         std::vector<char>& bytes = result->utf;
    265         while (cursor < end) {
    266             SkUnichar u = SkUTF::NextUTF8(&cursor, end);
    267 
    268             switch (fEncoding) {
    269                 case SkTextEncoding::kUTF8: {
    270                     char buffer[SkUTF::kMaxBytesInUTF8Sequence];
    271                     size_t count = SkUTF::ToUTF8(u, buffer);
    272                     result->utf.insert(bytes.end(), buffer, buffer + count);
    273                     break;
    274                 }
    275                 case SkTextEncoding::kUTF16: {
    276                     uint16_t buffer[2];
    277                     size_t count = SkUTF::ToUTF16(u, buffer);
    278                     result->utf.insert(bytes.end(), (char *)buffer, (char *)buffer + count * 2);
    279                     break;
    280                 }
    281                 case SkTextEncoding::kUTF32: {
    282                     result->utf.insert(bytes.end(), (char*) &u, (char*) &u + 4);
    283                     break;
    284                 }
    285                 default:
    286                     SK_ABORT("Bad encoding");
    287             }
    288         }
    289 
    290         return result;
    291     }
    292 
    293     SkTextEncoding fEncoding;
    294     std::vector<std::unique_ptr<Line>> fLines;
    295     std::vector<SkGlyphID> fGlyphIds;
    296     sk_sp<SkTypeface> fTypeface;
    297     const char* (*fText);
    298     int fLineCount;
    299     const char* fName;
    300 };
    301 
    302 DEF_BENCH(return new UtfToGlyph(SkTextEncoding::kUTF32, ctext, SK_ARRAY_COUNT(ctext),
    303                                 "SkTypefaceUTF32ToGlyphCN");)
    304 DEF_BENCH(return new UtfToGlyph(SkTextEncoding::kUTF16, ctext, SK_ARRAY_COUNT(ctext),
    305                                 "SkTypefaceUTF16ToGlyphCN");)
    306 DEF_BENCH(return new UtfToGlyph(SkTextEncoding::kUTF8, ctext, SK_ARRAY_COUNT(ctext),
    307                                 "SkTypefaceUTF8ToGlyphCN");)
    308 
    309 
    310 DEF_BENCH(return new UtfToGlyph(SkTextEncoding::kUTF32, atext, SK_ARRAY_COUNT(atext),
    311                                 "SkTypefaceUTF32ToGlyphAscii");)
    312 DEF_BENCH(return new UtfToGlyph(SkTextEncoding::kUTF16, atext, SK_ARRAY_COUNT(atext),
    313                                 "SkTypefaceUTF16ToGlyphAscii");)
    314 DEF_BENCH(return new UtfToGlyph(SkTextEncoding::kUTF8, atext, SK_ARRAY_COUNT(atext),
    315                                 "SkTypefaceUTF8ToGlyphAscii");)
    316 
    317 
    318 
    319