MorphologyBench.cpp revision e1ca705cac4b946993f6cbf798e2a0ba27e739f3
1/*
2 * Copyright 2012 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 "SkBenchmark.h"
9#include "SkCanvas.h"
10#include "SkPaint.h"
11#include "SkRandom.h"
12#include "SkShader.h"
13#include "SkString.h"
14#include "SkMorphologyImageFilter.h"
15
16#define SMALL   SkIntToScalar(2)
17#define REAL    1.5f
18#define BIG     SkIntToScalar(10)
19
20enum MorphologyType {
21    kErode_MT,
22    kDilate_MT
23};
24
25static const char* gStyleName[] = {
26    "erode",
27    "dilate"
28};
29
30class MorphologyBench : public SkBenchmark {
31    SkScalar       fRadius;
32    MorphologyType fStyle;
33    SkString       fName;
34
35public:
36    MorphologyBench(SkScalar rad, MorphologyType style)
37         {
38        fRadius = rad;
39        fStyle = style;
40        const char* name = rad > 0 ? gStyleName[style] : "none";
41        if (SkScalarFraction(rad) != 0) {
42            fName.printf("morph_%.2f_%s", SkScalarToFloat(rad), name);
43        } else {
44            fName.printf("morph_%d_%s", SkScalarRoundToInt(rad), name);
45        }
46    }
47
48protected:
49    virtual const char* onGetName() {
50        return fName.c_str();
51    }
52
53    virtual void onDraw(const int loops, SkCanvas* canvas) {
54        SkPaint paint;
55        this->setupPaint(&paint);
56
57        paint.setAntiAlias(true);
58
59        SkRandom rand;
60        for (int i = 0; i < loops; i++) {
61            SkRect r = SkRect::MakeWH(rand.nextUScalar1() * 400,
62                                      rand.nextUScalar1() * 400);
63            r.offset(fRadius, fRadius);
64
65            if (fRadius > 0) {
66                SkMorphologyImageFilter* mf = NULL;
67                switch (fStyle) {
68                case kDilate_MT:
69                    mf = new SkDilateImageFilter(SkScalarFloorToInt(fRadius),
70                                                 SkScalarFloorToInt(fRadius));
71                    break;
72                case kErode_MT:
73                    mf = new SkErodeImageFilter(SkScalarFloorToInt(fRadius),
74                                                SkScalarFloorToInt(fRadius));
75                    break;
76                }
77                paint.setImageFilter(mf)->unref();
78            }
79            canvas->drawOval(r, paint);
80        }
81    }
82
83private:
84    typedef SkBenchmark INHERITED;
85};
86
87DEF_BENCH( return new MorphologyBench(SMALL, kErode_MT); )
88DEF_BENCH( return new MorphologyBench(SMALL, kDilate_MT); )
89
90DEF_BENCH( return new MorphologyBench(BIG, kErode_MT); )
91DEF_BENCH( return new MorphologyBench(BIG, kDilate_MT); )
92
93DEF_BENCH( return new MorphologyBench(REAL, kErode_MT); )
94DEF_BENCH( return new MorphologyBench(REAL, kDilate_MT); )
95
96DEF_BENCH( return new MorphologyBench(0, kErode_MT); )
97