Create GLSLUniformHandler class for gpu backend
[platform/upstream/libSkiaSharp.git] / bench / nanobench.cpp
1 /*
2  * Copyright 2014 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 <ctype.h>
9
10 #include "nanobench.h"
11
12 #include "Benchmark.h"
13 #include "BitmapRegionDecoderBench.h"
14 #include "CodecBench.h"
15 #include "CodecBenchPriv.h"
16 #include "CrashHandler.h"
17 #include "DecodingBench.h"
18 #include "GMBench.h"
19 #include "ProcStats.h"
20 #include "ResultsWriter.h"
21 #include "RecordingBench.h"
22 #include "SKPAnimationBench.h"
23 #include "SKPBench.h"
24 #include "SubsetSingleBench.h"
25 #include "SubsetTranslateBench.h"
26 #include "SubsetZoomBench.h"
27 #include "Stats.h"
28
29 #include "SkBitmapRegionDecoder.h"
30 #include "SkBBoxHierarchy.h"
31 #include "SkCanvas.h"
32 #include "SkCodec.h"
33 #include "SkCommonFlags.h"
34 #include "SkData.h"
35 #include "SkForceLinking.h"
36 #include "SkGraphics.h"
37 #include "SkOSFile.h"
38 #include "SkPictureRecorder.h"
39 #include "SkPictureUtils.h"
40 #include "SkString.h"
41 #include "SkSurface.h"
42 #include "SkTaskGroup.h"
43
44 #include <stdlib.h>
45
46 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
47     #include "nanobenchAndroid.h"
48 #endif
49
50 #if SK_SUPPORT_GPU
51     #include "gl/GrGLDefines.h"
52     #include "GrCaps.h"
53     #include "GrContextFactory.h"
54     SkAutoTDelete<GrContextFactory> gGrFactory;
55 #endif
56
57     struct GrContextOptions;
58
59 __SK_FORCE_IMAGE_DECODER_LINKING;
60
61 static const int kAutoTuneLoops = 0;
62
63 static const int kDefaultLoops =
64 #ifdef SK_DEBUG
65     1;
66 #else
67     kAutoTuneLoops;
68 #endif
69
70 static SkString loops_help_txt() {
71     SkString help;
72     help.printf("Number of times to run each bench. Set this to %d to auto-"
73                 "tune for each bench. Timings are only reported when auto-tuning.",
74                 kAutoTuneLoops);
75     return help;
76 }
77
78 static SkString to_string(int n) {
79     SkString str;
80     str.appendS32(n);
81     return str;
82 }
83
84 DEFINE_int32(loops, kDefaultLoops, loops_help_txt().c_str());
85
86 DEFINE_int32(samples, 10, "Number of samples to measure for each bench.");
87 DEFINE_int32(ms, 0, "If >0, run each bench for this many ms instead of obeying --samples.");
88 DEFINE_int32(overheadLoops, 100000, "Loops to estimate timer overhead.");
89 DEFINE_double(overheadGoal, 0.0001,
90               "Loop until timer overhead is at most this fraction of our measurments.");
91 DEFINE_double(gpuMs, 5, "Target bench time in millseconds for GPU.");
92 DEFINE_int32(gpuFrameLag, 5, "If unknown, estimated maximum number of frames GPU allows to lag.");
93 DEFINE_bool(gpuCompressAlphaMasks, false, "Compress masks generated from falling back to "
94                                           "software path rendering.");
95
96 DEFINE_string(outResultsFile, "", "If given, write results here as JSON.");
97 DEFINE_int32(maxCalibrationAttempts, 3,
98              "Try up to this many times to guess loops for a bench, or skip the bench.");
99 DEFINE_int32(maxLoops, 1000000, "Never run a bench more times than this.");
100 DEFINE_string(clip, "0,0,1000,1000", "Clip for SKPs.");
101 DEFINE_string(scales, "1.0", "Space-separated scales for SKPs.");
102 DEFINE_string(zoom, "1.0,0", "Comma-separated zoomMax,zoomPeriodMs factors for a periodic SKP zoom "
103                              "function that ping-pongs between 1.0 and zoomMax.");
104 DEFINE_bool(bbh, true, "Build a BBH for SKPs?");
105 DEFINE_bool(mpd, true, "Use MultiPictureDraw for the SKPs?");
106 DEFINE_bool(loopSKP, true, "Loop SKPs like we do for micro benches?");
107 DEFINE_int32(flushEvery, 10, "Flush --outResultsFile every Nth run.");
108 DEFINE_bool(resetGpuContext, true, "Reset the GrContext before running each test.");
109 DEFINE_bool(gpuStats, false, "Print GPU stats after each gpu benchmark?");
110 DEFINE_bool(gpuStatsDump, false, "Dump GPU states after each benchmark to json");
111
112 static double now_ms() { return SkTime::GetNSecs() * 1e-6; }
113
114 static SkString humanize(double ms) {
115     if (FLAGS_verbose) return SkStringPrintf("%llu", (uint64_t)(ms*1e6));
116     return HumanizeMs(ms);
117 }
118 #define HUMANIZE(ms) humanize(ms).c_str()
119
120 bool Target::init(SkImageInfo info, Benchmark* bench) {
121     if (Benchmark::kRaster_Backend == config.backend) {
122         this->surface.reset(SkSurface::NewRaster(info));
123         if (!this->surface.get()) {
124             return false;
125         }
126     }
127     return true;
128 }
129 bool Target::capturePixels(SkBitmap* bmp) {
130     SkCanvas* canvas = this->getCanvas();
131     if (!canvas) {
132         return false;
133     }
134     bmp->setInfo(canvas->imageInfo());
135     if (!canvas->readPixels(bmp, 0, 0)) {
136         SkDebugf("Can't read canvas pixels.\n");
137         return false;
138     }
139     return true;
140 }
141
142 #if SK_SUPPORT_GPU
143 struct GPUTarget : public Target {
144     explicit GPUTarget(const Config& c) : Target(c), gl(nullptr) { }
145     SkGLContext* gl;
146
147     void setup() override {
148         this->gl->makeCurrent();
149         // Make sure we're done with whatever came before.
150         SK_GL(*this->gl, Finish());
151     }
152     void endTiming() override {
153         if (this->gl) {
154             SK_GL(*this->gl, Flush());
155             this->gl->swapBuffers();
156         }
157     }
158     void fence() override {
159         SK_GL(*this->gl, Finish());
160     }
161
162     bool needsFrameTiming(int* maxFrameLag) const override {
163         if (!this->gl->getMaxGpuFrameLag(maxFrameLag)) {
164             // Frame lag is unknown.
165             *maxFrameLag = FLAGS_gpuFrameLag;
166         }
167         return true;
168     }
169     bool init(SkImageInfo info, Benchmark* bench) override {
170         uint32_t flags = this->config.useDFText ? SkSurfaceProps::kUseDeviceIndependentFonts_Flag :
171                                                   0;
172         SkSurfaceProps props(flags, SkSurfaceProps::kLegacyFontHost_InitType);
173         this->surface.reset(SkSurface::NewRenderTarget(gGrFactory->get(this->config.ctxType),
174                                                          SkSurface::kNo_Budgeted, info,
175                                                          this->config.samples, &props));
176         this->gl = gGrFactory->getContextInfo(this->config.ctxType)->fGLContext;
177         if (!this->surface.get()) {
178             return false;
179         }
180         if (!this->gl->fenceSyncSupport()) {
181             SkDebugf("WARNING: GL context for config \"%s\" does not support fence sync. "
182                      "Timings might not be accurate.\n", this->config.name);
183         }
184         return true;
185     }
186     void fillOptions(ResultsWriter* log) override {
187         const GrGLubyte* version;
188         SK_GL_RET(*this->gl, version, GetString(GR_GL_VERSION));
189         log->configOption("GL_VERSION", (const char*)(version));
190
191         SK_GL_RET(*this->gl, version, GetString(GR_GL_RENDERER));
192         log->configOption("GL_RENDERER", (const char*) version);
193
194         SK_GL_RET(*this->gl, version, GetString(GR_GL_VENDOR));
195         log->configOption("GL_VENDOR", (const char*) version);
196
197         SK_GL_RET(*this->gl, version, GetString(GR_GL_SHADING_LANGUAGE_VERSION));
198         log->configOption("GL_SHADING_LANGUAGE_VERSION", (const char*) version);
199     }
200 };
201
202 #endif
203
204 static double time(int loops, Benchmark* bench, Target* target) {
205     SkCanvas* canvas = target->getCanvas();
206     if (canvas) {
207         canvas->clear(SK_ColorWHITE);
208     }
209     bench->preDraw(canvas);
210     double start = now_ms();
211     canvas = target->beginTiming(canvas);
212     bench->draw(loops, canvas);
213     if (canvas) {
214         canvas->flush();
215     }
216     target->endTiming();
217     double elapsed = now_ms() - start;
218     bench->postDraw(canvas);
219     return elapsed;
220 }
221
222 static double estimate_timer_overhead() {
223     double overhead = 0;
224     for (int i = 0; i < FLAGS_overheadLoops; i++) {
225         double start = now_ms();
226         overhead += now_ms() - start;
227     }
228     return overhead / FLAGS_overheadLoops;
229 }
230
231 static int detect_forever_loops(int loops) {
232     // look for a magic run-forever value
233     if (loops < 0) {
234         loops = SK_MaxS32;
235     }
236     return loops;
237 }
238
239 static int clamp_loops(int loops) {
240     if (loops < 1) {
241         SkDebugf("ERROR: clamping loops from %d to 1. "
242                  "There's probably something wrong with the bench.\n", loops);
243         return 1;
244     }
245     if (loops > FLAGS_maxLoops) {
246         SkDebugf("WARNING: clamping loops from %d to FLAGS_maxLoops, %d.\n", loops, FLAGS_maxLoops);
247         return FLAGS_maxLoops;
248     }
249     return loops;
250 }
251
252 static bool write_canvas_png(Target* target, const SkString& filename) {
253
254     if (filename.isEmpty()) {
255         return false;
256     }
257     if (target->getCanvas() &&
258         kUnknown_SkColorType == target->getCanvas()->imageInfo().colorType()) {
259         return false;
260     }
261
262     SkBitmap bmp;
263
264     if (!target->capturePixels(&bmp)) {
265         return false;
266     }
267
268     SkString dir = SkOSPath::Dirname(filename.c_str());
269     if (!sk_mkdir(dir.c_str())) {
270         SkDebugf("Can't make dir %s.\n", dir.c_str());
271         return false;
272     }
273     SkFILEWStream stream(filename.c_str());
274     if (!stream.isValid()) {
275         SkDebugf("Can't write %s.\n", filename.c_str());
276         return false;
277     }
278     if (!SkImageEncoder::EncodeStream(&stream, bmp, SkImageEncoder::kPNG_Type, 100)) {
279         SkDebugf("Can't encode a PNG.\n");
280         return false;
281     }
282     return true;
283 }
284
285 static int kFailedLoops = -2;
286 static int setup_cpu_bench(const double overhead, Target* target, Benchmark* bench) {
287     // First figure out approximately how many loops of bench it takes to make overhead negligible.
288     double bench_plus_overhead = 0.0;
289     int round = 0;
290     int loops = bench->calculateLoops(FLAGS_loops);
291     if (kAutoTuneLoops == loops) {
292         while (bench_plus_overhead < overhead) {
293             if (round++ == FLAGS_maxCalibrationAttempts) {
294                 SkDebugf("WARNING: Can't estimate loops for %s (%s vs. %s); skipping.\n",
295                          bench->getUniqueName(), HUMANIZE(bench_plus_overhead), HUMANIZE(overhead));
296                 return kFailedLoops;
297             }
298             bench_plus_overhead = time(1, bench, target);
299         }
300     }
301
302     // Later we'll just start and stop the timer once but loop N times.
303     // We'll pick N to make timer overhead negligible:
304     //
305     //          overhead
306     //  -------------------------  < FLAGS_overheadGoal
307     //  overhead + N * Bench Time
308     //
309     // where bench_plus_overhead â‰ˆ overhead + Bench Time.
310     //
311     // Doing some math, we get:
312     //
313     //  (overhead / FLAGS_overheadGoal) - overhead
314     //  ------------------------------------------  < N
315     //       bench_plus_overhead - overhead)
316     //
317     // Luckily, this also works well in practice. :)
318     if (kAutoTuneLoops == loops) {
319         const double numer = overhead / FLAGS_overheadGoal - overhead;
320         const double denom = bench_plus_overhead - overhead;
321         loops = (int)ceil(numer / denom);
322         loops = clamp_loops(loops);
323     } else {
324         loops = detect_forever_loops(loops);
325     }
326
327     return loops;
328 }
329
330 static int setup_gpu_bench(Target* target, Benchmark* bench, int maxGpuFrameLag) {
331     // First, figure out how many loops it'll take to get a frame up to FLAGS_gpuMs.
332     int loops = bench->calculateLoops(FLAGS_loops);
333     if (kAutoTuneLoops == loops) {
334         loops = 1;
335         double elapsed = 0;
336         do {
337             if (1<<30 == loops) {
338                 // We're about to wrap.  Something's wrong with the bench.
339                 loops = 0;
340                 break;
341             }
342             loops *= 2;
343             // If the GPU lets frames lag at all, we need to make sure we're timing
344             // _this_ round, not still timing last round.
345             for (int i = 0; i < maxGpuFrameLag; i++) {
346                 elapsed = time(loops, bench, target);
347             }
348         } while (elapsed < FLAGS_gpuMs);
349
350         // We've overshot at least a little.  Scale back linearly.
351         loops = (int)ceil(loops * FLAGS_gpuMs / elapsed);
352         loops = clamp_loops(loops);
353
354         // Make sure we're not still timing our calibration.
355         target->fence();
356     } else {
357         loops = detect_forever_loops(loops);
358     }
359
360     // Pretty much the same deal as the calibration: do some warmup to make
361     // sure we're timing steady-state pipelined frames.
362     for (int i = 0; i < maxGpuFrameLag - 1; i++) {
363         time(loops, bench, target);
364     }
365
366     return loops;
367 }
368
369 static SkString to_lower(const char* str) {
370     SkString lower(str);
371     for (size_t i = 0; i < lower.size(); i++) {
372         lower[i] = tolower(lower[i]);
373     }
374     return lower;
375 }
376
377 static bool is_cpu_config_allowed(const char* name) {
378     for (int i = 0; i < FLAGS_config.count(); i++) {
379         if (to_lower(FLAGS_config[i]).equals(name)) {
380             return true;
381         }
382     }
383     return false;
384 }
385
386 #if SK_SUPPORT_GPU
387 static bool is_gpu_config_allowed(const char* name, GrContextFactory::GLContextType ctxType,
388                                   int sampleCnt) {
389     if (!is_cpu_config_allowed(name)) {
390         return false;
391     }
392     if (const GrContext* ctx = gGrFactory->get(ctxType)) {
393         return sampleCnt <= ctx->caps()->maxSampleCount();
394     }
395     return false;
396 }
397 #endif
398
399 #if SK_SUPPORT_GPU
400 #define kBogusGLContextType GrContextFactory::kNative_GLContextType
401 #else
402 #define kBogusGLContextType 0
403 #endif
404
405 // Append all configs that are enabled and supported.
406 static void create_configs(SkTDArray<Config>* configs) {
407     #define CPU_CONFIG(name, backend, color, alpha)                       \
408         if (is_cpu_config_allowed(#name)) {                               \
409             Config config = { #name, Benchmark::backend, color, alpha, 0, \
410                               kBogusGLContextType, false };               \
411             configs->push(config);                                        \
412         }
413
414     if (FLAGS_cpu) {
415         CPU_CONFIG(nonrendering, kNonRendering_Backend, kUnknown_SkColorType, kUnpremul_SkAlphaType)
416         CPU_CONFIG(8888, kRaster_Backend, kN32_SkColorType, kPremul_SkAlphaType)
417         CPU_CONFIG(565, kRaster_Backend, kRGB_565_SkColorType, kOpaque_SkAlphaType)
418     }
419
420 #if SK_SUPPORT_GPU
421     #define GPU_CONFIG(name, ctxType, samples, useDFText)                        \
422         if (is_gpu_config_allowed(#name, GrContextFactory::ctxType, samples)) {  \
423             Config config = {                                                    \
424                 #name,                                                           \
425                 Benchmark::kGPU_Backend,                                         \
426                 kN32_SkColorType,                                                \
427                 kPremul_SkAlphaType,                                             \
428                 samples,                                                         \
429                 GrContextFactory::ctxType,                                       \
430                 useDFText };                                                     \
431             configs->push(config);                                               \
432         }
433
434     if (FLAGS_gpu) {
435         GPU_CONFIG(gpu, kNative_GLContextType, 0, false)
436         GPU_CONFIG(msaa4, kNative_GLContextType, 4, false)
437         GPU_CONFIG(msaa16, kNative_GLContextType, 16, false)
438         GPU_CONFIG(nvprmsaa4, kNVPR_GLContextType, 4, false)
439         GPU_CONFIG(nvprmsaa16, kNVPR_GLContextType, 16, false)
440         GPU_CONFIG(gpudft, kNative_GLContextType, 0, true)
441         GPU_CONFIG(debug, kDebug_GLContextType, 0, false)
442         GPU_CONFIG(nullgpu, kNull_GLContextType, 0, false)
443 #ifdef SK_ANGLE
444         GPU_CONFIG(angle, kANGLE_GLContextType, 0, false)
445         GPU_CONFIG(angle-gl, kANGLE_GL_GLContextType, 0, false)
446 #endif
447 #ifdef SK_COMMAND_BUFFER
448         GPU_CONFIG(commandbuffer, kCommandBuffer_GLContextType, 0, false)
449 #endif
450 #if SK_MESA
451         GPU_CONFIG(mesa, kMESA_GLContextType, 0, false)
452 #endif
453     }
454 #endif
455
456 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
457     if (is_cpu_config_allowed("hwui")) {
458         Config config = { "hwui", Benchmark::kHWUI_Backend, kRGBA_8888_SkColorType,
459                           kPremul_SkAlphaType, 0, kBogusGLContextType, false };
460         configs->push(config);
461     }
462 #endif
463 }
464
465 // If bench is enabled for config, returns a Target* for it, otherwise nullptr.
466 static Target* is_enabled(Benchmark* bench, const Config& config) {
467     if (!bench->isSuitableFor(config.backend)) {
468         return nullptr;
469     }
470
471     SkImageInfo info = SkImageInfo::Make(bench->getSize().fX, bench->getSize().fY,
472                                          config.color, config.alpha);
473
474     Target* target = nullptr;
475
476     switch (config.backend) {
477 #if SK_SUPPORT_GPU
478     case Benchmark::kGPU_Backend:
479         target = new GPUTarget(config);
480         break;
481 #endif
482 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
483     case Benchmark::kHWUI_Backend:
484         target = new HWUITarget(config, bench);
485         break;
486 #endif
487     default:
488         target = new Target(config);
489         break;
490     }
491
492     if (!target->init(info, bench)) {
493         delete target;
494         return nullptr;
495     }
496     return target;
497 }
498
499 /*
500  * We only run our subset benches on files that are supported by BitmapRegionDecoder:
501  * i.e. PNG, JPEG, and WEBP. We do *not* test WEBP, since we do not have a scanline
502  * decoder for WEBP, which is necessary for running the subset bench. (Another bench
503  * must be used to test WEBP, which decodes subsets natively.)
504  */
505 static bool run_subset_bench(const SkString& path) {
506     static const char* const exts[] = {
507         "jpg", "jpeg", "png",
508         "JPG", "JPEG", "PNG",
509     };
510
511     for (uint32_t i = 0; i < SK_ARRAY_COUNT(exts); i++) {
512         if (path.endsWith(exts[i])) {
513             return true;
514         }
515     }
516
517     return false;
518 }
519
520 /*
521  * Returns true if set up for a subset decode succeeds, false otherwise
522  * If the set-up succeeds, the width and height parameters will be set
523  */
524 static bool valid_subset_bench(const SkString& path, SkColorType colorType,
525         int* width, int* height) {
526     SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(path.c_str()));
527     SkAutoTDelete<SkMemoryStream> stream(new SkMemoryStream(encoded));
528
529     // Check that we can create a codec.
530     SkAutoTDelete<SkCodec> codec(SkCodec::NewFromStream(stream.detach()));
531     if (nullptr == codec) {
532         SkDebugf("Could not create codec for %s.  Skipping bench.\n", path.c_str());
533         return false;
534     }
535
536     // These will be initialized by SkCodec if the color type is kIndex8 and
537     // unused otherwise.
538     SkPMColor colors[256];
539     int colorCount;
540     const SkImageInfo info = codec->getInfo().makeColorType(colorType);
541     if (codec->startScanlineDecode(info, nullptr, colors, &colorCount) != SkCodec::kSuccess)
542     {
543         SkDebugf("Could not create scanline decoder for %s with color type %s.  "
544                 "Skipping bench.\n", path.c_str(), color_type_to_str(colorType));
545         return false;
546     }
547     *width = info.width();
548     *height = info.height();
549
550     // Check if the image is large enough for a meaningful subset benchmark.
551     if (*width <= 512 && *height <= 512) {
552         // This should not print a message since it is not an error.
553         return false;
554     }
555
556     return true;
557 }
558
559 static bool valid_brd_bench(SkData* encoded, SkBitmapRegionDecoder::Strategy strategy,
560         SkColorType colorType, uint32_t sampleSize, uint32_t minOutputSize, int* width,
561         int* height) {
562     SkAutoTDelete<SkBitmapRegionDecoder> brd(
563             SkBitmapRegionDecoder::Create(encoded, strategy));
564     if (nullptr == brd.get()) {
565         // This is indicates that subset decoding is not supported for a particular image format.
566         return false;
567     }
568
569     SkBitmap bitmap;
570     if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(0, 0, brd->width(), brd->height()),
571             1, colorType, false)) {
572         return false;
573     }
574
575     if (sampleSize * minOutputSize > (uint32_t) brd->width() || sampleSize * minOutputSize >
576             (uint32_t) brd->height()) {
577         // This indicates that the image is not large enough to decode a
578         // minOutputSize x minOutputSize subset at the given sampleSize.
579         return false;
580     }
581
582     // Set the image width and height.  The calling code will use this to choose subsets to decode.
583     *width = brd->width();
584     *height = brd->height();
585     return true;
586 }
587
588 static void cleanup_run(Target* target) {
589     delete target;
590 #if SK_SUPPORT_GPU
591     if (FLAGS_abandonGpuContext) {
592         gGrFactory->abandonContexts();
593     }
594     if (FLAGS_resetGpuContext || FLAGS_abandonGpuContext) {
595         gGrFactory->destroyContexts();
596     }
597 #endif
598 }
599
600 class BenchmarkStream {
601 public:
602     BenchmarkStream() : fBenches(BenchRegistry::Head())
603                       , fGMs(skiagm::GMRegistry::Head())
604                       , fCurrentRecording(0)
605                       , fCurrentScale(0)
606                       , fCurrentSKP(0)
607                       , fCurrentUseMPD(0)
608                       , fCurrentCodec(0)
609                       , fCurrentImage(0)
610                       , fCurrentSubsetImage(0)
611                       , fCurrentBRDImage(0)
612                       , fCurrentColorType(0)
613                       , fCurrentSubsetType(0)
614                       , fCurrentBRDStrategy(0)
615                       , fCurrentBRDSampleSize(0)
616                       , fCurrentAnimSKP(0) {
617         for (int i = 0; i < FLAGS_skps.count(); i++) {
618             if (SkStrEndsWith(FLAGS_skps[i], ".skp")) {
619                 fSKPs.push_back() = FLAGS_skps[i];
620             } else {
621                 SkOSFile::Iter it(FLAGS_skps[i], ".skp");
622                 SkString path;
623                 while (it.next(&path)) {
624                     fSKPs.push_back() = SkOSPath::Join(FLAGS_skps[0], path.c_str());
625                 }
626             }
627         }
628
629         if (4 != sscanf(FLAGS_clip[0], "%d,%d,%d,%d",
630                         &fClip.fLeft, &fClip.fTop, &fClip.fRight, &fClip.fBottom)) {
631             SkDebugf("Can't parse %s from --clip as an SkIRect.\n", FLAGS_clip[0]);
632             exit(1);
633         }
634
635         for (int i = 0; i < FLAGS_scales.count(); i++) {
636             if (1 != sscanf(FLAGS_scales[i], "%f", &fScales.push_back())) {
637                 SkDebugf("Can't parse %s from --scales as an SkScalar.\n", FLAGS_scales[i]);
638                 exit(1);
639             }
640         }
641
642         if (2 != sscanf(FLAGS_zoom[0], "%f,%lf", &fZoomMax, &fZoomPeriodMs)) {
643             SkDebugf("Can't parse %s from --zoom as a zoomMax,zoomPeriodMs.\n", FLAGS_zoom[0]);
644             exit(1);
645         }
646
647         if (FLAGS_mpd) {
648             fUseMPDs.push_back() = true;
649         }
650         fUseMPDs.push_back() = false;
651
652         // Prepare the images for decoding
653         for (int i = 0; i < FLAGS_images.count(); i++) {
654             const char* flag = FLAGS_images[i];
655             if (sk_isdir(flag)) {
656                 // If the value passed in is a directory, add all the images
657                 SkOSFile::Iter it(flag);
658                 SkString file;
659                 while (it.next(&file)) {
660                     fImages.push_back() = SkOSPath::Join(flag, file.c_str());
661                 }
662             } else if (sk_exists(flag)) {
663                 // Also add the value if it is a single image
664                 fImages.push_back() = flag;
665             }
666         }
667
668         // Choose the candidate color types for image decoding
669         const SkColorType colorTypes[] =
670             { kN32_SkColorType,
671               kRGB_565_SkColorType,
672               kAlpha_8_SkColorType,
673               kIndex_8_SkColorType,
674               kGray_8_SkColorType };
675         fColorTypes.reset(colorTypes, SK_ARRAY_COUNT(colorTypes));
676     }
677
678     static bool ReadPicture(const char* path, SkAutoTUnref<SkPicture>* pic) {
679         // Not strictly necessary, as it will be checked again later,
680         // but helps to avoid a lot of pointless work if we're going to skip it.
681         if (SkCommandLineFlags::ShouldSkip(FLAGS_match, path)) {
682             return false;
683         }
684
685         SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(path));
686         if (stream.get() == nullptr) {
687             SkDebugf("Could not read %s.\n", path);
688             return false;
689         }
690
691         pic->reset(SkPicture::CreateFromStream(stream.get()));
692         if (pic->get() == nullptr) {
693             SkDebugf("Could not read %s as an SkPicture.\n", path);
694             return false;
695         }
696         return true;
697     }
698
699     Benchmark* next() {
700         if (fBenches) {
701             Benchmark* bench = fBenches->factory()(nullptr);
702             fBenches = fBenches->next();
703             fSourceType = "bench";
704             fBenchType  = "micro";
705             return bench;
706         }
707
708         while (fGMs) {
709             SkAutoTDelete<skiagm::GM> gm(fGMs->factory()(nullptr));
710             fGMs = fGMs->next();
711             if (gm->runAsBench()) {
712                 fSourceType = "gm";
713                 fBenchType  = "micro";
714                 return new GMBench(gm.detach());
715             }
716         }
717
718         // First add all .skps as RecordingBenches.
719         while (fCurrentRecording < fSKPs.count()) {
720             const SkString& path = fSKPs[fCurrentRecording++];
721             SkAutoTUnref<SkPicture> pic;
722             if (!ReadPicture(path.c_str(), &pic)) {
723                 continue;
724             }
725             SkString name = SkOSPath::Basename(path.c_str());
726             fSourceType = "skp";
727             fBenchType  = "recording";
728             fSKPBytes = static_cast<double>(SkPictureUtils::ApproximateBytesUsed(pic));
729             fSKPOps   = pic->approximateOpCount();
730             return new RecordingBench(name.c_str(), pic.get(), FLAGS_bbh);
731         }
732
733         // Then once each for each scale as SKPBenches (playback).
734         while (fCurrentScale < fScales.count()) {
735             while (fCurrentSKP < fSKPs.count()) {
736                 const SkString& path = fSKPs[fCurrentSKP];
737                 SkAutoTUnref<SkPicture> pic;
738                 if (!ReadPicture(path.c_str(), &pic)) {
739                     fCurrentSKP++;
740                     continue;
741                 }
742
743                 while (fCurrentUseMPD < fUseMPDs.count()) {
744                     if (FLAGS_bbh) {
745                         // The SKP we read off disk doesn't have a BBH.  Re-record so it grows one.
746                         SkRTreeFactory factory;
747                         SkPictureRecorder recorder;
748                         static const int kFlags = SkPictureRecorder::kComputeSaveLayerInfo_RecordFlag;
749                         pic->playback(recorder.beginRecording(pic->cullRect().width(),
750                                                               pic->cullRect().height(),
751                                                               &factory,
752                                                               fUseMPDs[fCurrentUseMPD] ? kFlags : 0));
753                         pic.reset(recorder.endRecording());
754                     }
755                     SkString name = SkOSPath::Basename(path.c_str());
756                     fSourceType = "skp";
757                     fBenchType = "playback";
758                     return new SKPBench(name.c_str(), pic.get(), fClip, fScales[fCurrentScale],
759                                         fUseMPDs[fCurrentUseMPD++], FLAGS_loopSKP);
760                 }
761                 fCurrentUseMPD = 0;
762                 fCurrentSKP++;
763             }
764             fCurrentSKP = 0;
765             fCurrentScale++;
766         }
767
768         // Now loop over each skp again if we have an animation
769         if (fZoomMax != 1.0f && fZoomPeriodMs > 0) {
770             while (fCurrentAnimSKP < fSKPs.count()) {
771                 const SkString& path = fSKPs[fCurrentAnimSKP];
772                 SkAutoTUnref<SkPicture> pic;
773                 if (!ReadPicture(path.c_str(), &pic)) {
774                     fCurrentAnimSKP++;
775                     continue;
776                 }
777
778                 fCurrentAnimSKP++;
779                 SkString name = SkOSPath::Basename(path.c_str());
780                 SkAutoTUnref<SKPAnimationBench::Animation> animation(
781                     SKPAnimationBench::CreateZoomAnimation(fZoomMax, fZoomPeriodMs));
782                 return new SKPAnimationBench(name.c_str(), pic.get(), fClip, animation,
783                                              FLAGS_loopSKP);
784             }
785         }
786
787         for (; fCurrentCodec < fImages.count(); fCurrentCodec++) {
788             fSourceType = "image";
789             fBenchType = "skcodec";
790             const SkString& path = fImages[fCurrentCodec];
791             SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(path.c_str()));
792             SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
793             if (!codec) {
794                 // Nothing to time.
795                 SkDebugf("Cannot find codec for %s\n", path.c_str());
796                 continue;
797             }
798
799             while (fCurrentColorType < fColorTypes.count()) {
800                 const SkColorType colorType = fColorTypes[fCurrentColorType];
801                 fCurrentColorType++;
802
803                 // Make sure we can decode to this color type.
804                 SkImageInfo info = codec->getInfo().makeColorType(colorType);
805                 SkAlphaType alphaType;
806                 if (!SkColorTypeValidateAlphaType(colorType, info.alphaType(),
807                                                   &alphaType)) {
808                     continue;
809                 }
810                 if (alphaType != info.alphaType()) {
811                     info = info.makeAlphaType(alphaType);
812                 }
813
814                 const size_t rowBytes = info.minRowBytes();
815                 SkAutoMalloc storage(info.getSafeSize(rowBytes));
816
817                 // Used if fCurrentColorType is kIndex_8_SkColorType
818                 int colorCount = 256;
819                 SkPMColor colors[256];
820
821                 const SkCodec::Result result = codec->getPixels(
822                         info, storage.get(), rowBytes, nullptr, colors,
823                         &colorCount);
824                 switch (result) {
825                     case SkCodec::kSuccess:
826                     case SkCodec::kIncompleteInput:
827                         return new CodecBench(SkOSPath::Basename(path.c_str()),
828                                 encoded, colorType);
829                     case SkCodec::kInvalidConversion:
830                         // This is okay. Not all conversions are valid.
831                         break;
832                     default:
833                         // This represents some sort of failure.
834                         SkASSERT(false);
835                         break;
836                 }
837             }
838             fCurrentColorType = 0;
839         }
840
841         // Run the DecodingBenches
842         while (fCurrentImage < fImages.count()) {
843             fSourceType = "image";
844             fBenchType = "skimagedecoder";
845             while (fCurrentColorType < fColorTypes.count()) {
846                 const SkString& path = fImages[fCurrentImage];
847                 SkColorType colorType = fColorTypes[fCurrentColorType];
848                 fCurrentColorType++;
849                 // Check if the image decodes to the right color type
850                 // before creating the benchmark
851                 SkBitmap bitmap;
852                 if (SkImageDecoder::DecodeFile(path.c_str(), &bitmap,
853                         colorType, SkImageDecoder::kDecodePixels_Mode)
854                         && bitmap.colorType() == colorType) {
855                     return new DecodingBench(path, colorType);
856                 }
857             }
858             fCurrentColorType = 0;
859             fCurrentImage++;
860         }
861
862         // Run the SubsetBenches
863         while (fCurrentSubsetImage < fImages.count()) {
864             fSourceType = "image";
865             fBenchType = "skcodec";
866             const SkString& path = fImages[fCurrentSubsetImage];
867             if (!run_subset_bench(path)) {
868                 fCurrentSubsetImage++;
869                 continue;
870             }
871             while (fCurrentColorType < fColorTypes.count()) {
872                 SkColorType colorType = fColorTypes[fCurrentColorType];
873                 while (fCurrentSubsetType <= kLast_SubsetType) {
874                     int width = 0;
875                     int height = 0;
876                     int currentSubsetType = fCurrentSubsetType++;
877                     if (valid_subset_bench(path, colorType, &width, &height)) {
878                         switch (currentSubsetType) {
879                             case kTopLeft_SubsetType:
880                                 return new SubsetSingleBench(path, colorType, width/3,
881                                         height/3, 0, 0);
882                             case kTopRight_SubsetType:
883                                 return new SubsetSingleBench(path, colorType, width/3,
884                                         height/3, 2*width/3, 0);
885                             case kMiddle_SubsetType:
886                                 return new SubsetSingleBench(path, colorType, width/3,
887                                         height/3, width/3, height/3);
888                             case kBottomLeft_SubsetType:
889                                 return new SubsetSingleBench(path, colorType, width/3,
890                                         height/3, 0, 2*height/3);
891                             case kBottomRight_SubsetType:
892                                 return new SubsetSingleBench(path, colorType, width/3,
893                                         height/3, 2*width/3, 2*height/3);
894                             case kTranslate_SubsetType:
895                                 return new SubsetTranslateBench(path, colorType, 512, 512);
896                             case kZoom_SubsetType:
897                                 return new SubsetZoomBench(path, colorType, 512, 512);
898                         }
899                     } else {
900                         break;
901                     }
902                 }
903                 fCurrentSubsetType = 0;
904                 fCurrentColorType++;
905             }
906             fCurrentColorType = 0;
907             fCurrentSubsetImage++;
908         }
909
910         // Run the BRDBenches
911         // We will benchmark multiple BRD strategies.
912         static const struct {
913             SkBitmapRegionDecoder::Strategy    fStrategy;
914             const char*                        fName;
915         } strategies[] = {
916             { SkBitmapRegionDecoder::kCanvas_Strategy,       "BRD_canvas" },
917             { SkBitmapRegionDecoder::kAndroidCodec_Strategy, "BRD_android_codec" },
918         };
919
920         // We intend to create benchmarks that model the use cases in
921         // android/libraries/social/tiledimage.  In this library, an image is decoded in 512x512
922         // tiles.  The image can be translated freely, so the location of a tile may be anywhere in
923         // the image.  For that reason, we will benchmark decodes in five representative locations
924         // in the image.  Additionally, this use case utilizes power of two scaling, so we will
925         // test on power of two sample sizes.  The output tile is always 512x512, so, when a
926         // sampleSize is used, the size of the subset that is decoded is always
927         // (sampleSize*512)x(sampleSize*512).
928         // There are a few good reasons to only test on power of two sample sizes at this time:
929         //     JPEG decodes using kOriginal_Strategy are broken for non-powers of two.
930         //         https://bug.skia.org/4319
931         //     All use cases we are aware of only scale by powers of two.
932         //     PNG decodes use the indicated sampling strategy regardless of the sample size, so
933         //         these tests are sufficient to provide good coverage of our scaling options.
934         const uint32_t sampleSizes[] = { 1, 2, 4, 8, 16, 32, 64 };
935         const uint32_t minOutputSize = 512;
936         while (fCurrentBRDImage < fImages.count()) {
937             while (fCurrentBRDStrategy < (int) SK_ARRAY_COUNT(strategies)) {
938                 fSourceType = "image";
939                 fBenchType = strategies[fCurrentBRDStrategy].fName;
940
941                 const SkString& path = fImages[fCurrentBRDImage];
942                 const SkBitmapRegionDecoder::Strategy strategy =
943                         strategies[fCurrentBRDStrategy].fStrategy;
944
945                 while (fCurrentColorType < fColorTypes.count()) {
946                     while (fCurrentBRDSampleSize < (int) SK_ARRAY_COUNT(sampleSizes)) {
947                         while (fCurrentSubsetType <= kLastSingle_SubsetType) {
948
949
950                             SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(path.c_str()));
951                             const SkColorType colorType = fColorTypes[fCurrentColorType];
952                             uint32_t sampleSize = sampleSizes[fCurrentBRDSampleSize];
953                             int currentSubsetType = fCurrentSubsetType++;
954
955                             int width = 0;
956                             int height = 0;
957                             if (!valid_brd_bench(encoded.get(), strategy, colorType, sampleSize,
958                                     minOutputSize, &width, &height)) {
959                                 break;
960                             }
961
962                             SkString basename = SkOSPath::Basename(path.c_str());
963                             SkIRect subset;
964                             const uint32_t subsetSize = sampleSize * minOutputSize;
965                             switch (currentSubsetType) {
966                                 case kTopLeft_SubsetType:
967                                     basename.append("_TopLeft");
968                                     subset = SkIRect::MakeXYWH(0, 0, subsetSize, subsetSize);
969                                     break;
970                                 case kTopRight_SubsetType:
971                                     basename.append("_TopRight");
972                                     subset = SkIRect::MakeXYWH(width - subsetSize, 0, subsetSize,
973                                             subsetSize);
974                                     break;
975                                 case kMiddle_SubsetType:
976                                     basename.append("_Middle");
977                                     subset = SkIRect::MakeXYWH((width - subsetSize) / 2,
978                                             (height - subsetSize) / 2, subsetSize, subsetSize);
979                                     break;
980                                 case kBottomLeft_SubsetType:
981                                     basename.append("_BottomLeft");
982                                     subset = SkIRect::MakeXYWH(0, height - subsetSize, subsetSize,
983                                             subsetSize);
984                                     break;
985                                 case kBottomRight_SubsetType:
986                                     basename.append("_BottomRight");
987                                     subset = SkIRect::MakeXYWH(width - subsetSize,
988                                             height - subsetSize, subsetSize, subsetSize);
989                                     break;
990                                 default:
991                                     SkASSERT(false);
992                             }
993
994                             return new BitmapRegionDecoderBench(basename.c_str(), encoded.get(),
995                                     strategy, colorType, sampleSize, subset);
996                         }
997                         fCurrentSubsetType = 0;
998                         fCurrentBRDSampleSize++;
999                     }
1000                     fCurrentBRDSampleSize = 0;
1001                     fCurrentColorType++;
1002                 }
1003                 fCurrentColorType = 0;
1004                 fCurrentBRDStrategy++;
1005             }
1006             fCurrentBRDStrategy = 0;
1007             fCurrentBRDImage++;
1008         }
1009
1010         return nullptr;
1011     }
1012
1013     void fillCurrentOptions(ResultsWriter* log) const {
1014         log->configOption("source_type", fSourceType);
1015         log->configOption("bench_type",  fBenchType);
1016         if (0 == strcmp(fSourceType, "skp")) {
1017             log->configOption("clip",
1018                     SkStringPrintf("%d %d %d %d", fClip.fLeft, fClip.fTop,
1019                                                   fClip.fRight, fClip.fBottom).c_str());
1020             SK_ALWAYSBREAK(fCurrentScale < fScales.count());  // debugging paranoia
1021             log->configOption("scale", SkStringPrintf("%.2g", fScales[fCurrentScale]).c_str());
1022             if (fCurrentUseMPD > 0) {
1023                 SkASSERT(1 == fCurrentUseMPD || 2 == fCurrentUseMPD);
1024                 log->configOption("multi_picture_draw", fUseMPDs[fCurrentUseMPD-1] ? "true" : "false");
1025             }
1026         }
1027         if (0 == strcmp(fBenchType, "recording")) {
1028             log->metric("bytes", fSKPBytes);
1029             log->metric("ops",   fSKPOps);
1030         }
1031     }
1032
1033 private:
1034     enum SubsetType {
1035         kTopLeft_SubsetType     = 0,
1036         kTopRight_SubsetType    = 1,
1037         kMiddle_SubsetType      = 2,
1038         kBottomLeft_SubsetType  = 3,
1039         kBottomRight_SubsetType = 4,
1040         kTranslate_SubsetType   = 5,
1041         kZoom_SubsetType        = 6,
1042         kLast_SubsetType        = kZoom_SubsetType,
1043         kLastSingle_SubsetType  = kBottomRight_SubsetType,
1044     };
1045
1046     const BenchRegistry* fBenches;
1047     const skiagm::GMRegistry* fGMs;
1048     SkIRect            fClip;
1049     SkTArray<SkScalar> fScales;
1050     SkTArray<SkString> fSKPs;
1051     SkTArray<bool>     fUseMPDs;
1052     SkTArray<SkString> fImages;
1053     SkTArray<SkColorType, true> fColorTypes;
1054     SkScalar           fZoomMax;
1055     double             fZoomPeriodMs;
1056
1057     double fSKPBytes, fSKPOps;
1058
1059     const char* fSourceType;  // What we're benching: bench, GM, SKP, ...
1060     const char* fBenchType;   // How we bench it: micro, recording, playback, ...
1061     int fCurrentRecording;
1062     int fCurrentScale;
1063     int fCurrentSKP;
1064     int fCurrentUseMPD;
1065     int fCurrentCodec;
1066     int fCurrentImage;
1067     int fCurrentSubsetImage;
1068     int fCurrentBRDImage;
1069     int fCurrentColorType;
1070     int fCurrentSubsetType;
1071     int fCurrentBRDStrategy;
1072     int fCurrentBRDSampleSize;
1073     int fCurrentAnimSKP;
1074 };
1075
1076 int nanobench_main();
1077 int nanobench_main() {
1078     SetupCrashHandler();
1079     SkAutoGraphics ag;
1080     SkTaskGroup::Enabler enabled(FLAGS_threads);
1081
1082 #if SK_SUPPORT_GPU
1083     GrContextOptions grContextOpts;
1084     grContextOpts.fDrawPathToCompressedTexture = FLAGS_gpuCompressAlphaMasks;
1085     gGrFactory.reset(new GrContextFactory(grContextOpts));
1086 #endif
1087
1088     if (FLAGS_veryVerbose) {
1089         FLAGS_verbose = true;
1090     }
1091
1092     if (kAutoTuneLoops != FLAGS_loops) {
1093         FLAGS_samples     = 1;
1094         FLAGS_gpuFrameLag = 0;
1095     }
1096
1097     if (!FLAGS_writePath.isEmpty()) {
1098         SkDebugf("Writing files to %s.\n", FLAGS_writePath[0]);
1099         if (!sk_mkdir(FLAGS_writePath[0])) {
1100             SkDebugf("Could not create %s. Files won't be written.\n", FLAGS_writePath[0]);
1101             FLAGS_writePath.set(0, nullptr);
1102         }
1103     }
1104
1105     SkAutoTDelete<ResultsWriter> log(new ResultsWriter);
1106     if (!FLAGS_outResultsFile.isEmpty()) {
1107         log.reset(new NanoJSONResultsWriter(FLAGS_outResultsFile[0]));
1108     }
1109
1110     if (1 == FLAGS_properties.count() % 2) {
1111         SkDebugf("ERROR: --properties must be passed with an even number of arguments.\n");
1112         return 1;
1113     }
1114     for (int i = 1; i < FLAGS_properties.count(); i += 2) {
1115         log->property(FLAGS_properties[i-1], FLAGS_properties[i]);
1116     }
1117
1118     if (1 == FLAGS_key.count() % 2) {
1119         SkDebugf("ERROR: --key must be passed with an even number of arguments.\n");
1120         return 1;
1121     }
1122     for (int i = 1; i < FLAGS_key.count(); i += 2) {
1123         log->key(FLAGS_key[i-1], FLAGS_key[i]);
1124     }
1125
1126     const double overhead = estimate_timer_overhead();
1127     SkDebugf("Timer overhead: %s\n", HUMANIZE(overhead));
1128
1129     SkTArray<double> samples;
1130
1131     if (kAutoTuneLoops != FLAGS_loops) {
1132         SkDebugf("Fixed number of loops; times would only be misleading so we won't print them.\n");
1133     } else if (FLAGS_quiet) {
1134         SkDebugf("median\tbench\tconfig\n");
1135     } else if (FLAGS_ms) {
1136         SkDebugf("curr/maxrss\tloops\tmin\tmedian\tmean\tmax\tstddev\tsamples\tconfig\tbench\n");
1137     } else {
1138         SkDebugf("curr/maxrss\tloops\tmin\tmedian\tmean\tmax\tstddev\t%-*s\tconfig\tbench\n",
1139                  FLAGS_samples, "samples");
1140     }
1141
1142     SkTDArray<Config> configs;
1143     create_configs(&configs);
1144
1145     int runs = 0;
1146     BenchmarkStream benchStream;
1147     while (Benchmark* b = benchStream.next()) {
1148         SkAutoTDelete<Benchmark> bench(b);
1149         if (SkCommandLineFlags::ShouldSkip(FLAGS_match, bench->getUniqueName())) {
1150             continue;
1151         }
1152
1153         if (!configs.isEmpty()) {
1154             log->bench(bench->getUniqueName(), bench->getSize().fX, bench->getSize().fY);
1155             bench->delayedSetup();
1156         }
1157         for (int i = 0; i < configs.count(); ++i) {
1158             Target* target = is_enabled(b, configs[i]);
1159             if (!target) {
1160                 continue;
1161             }
1162
1163             // During HWUI output this canvas may be nullptr.
1164             SkCanvas* canvas = target->getCanvas();
1165             const char* config = target->config.name;
1166
1167             target->setup();
1168             bench->perCanvasPreDraw(canvas);
1169
1170             int maxFrameLag;
1171             int loops = target->needsFrameTiming(&maxFrameLag)
1172                 ? setup_gpu_bench(target, bench.get(), maxFrameLag)
1173                 : setup_cpu_bench(overhead, target, bench.get());
1174
1175             if (FLAGS_ms) {
1176                 samples.reset();
1177                 auto stop = now_ms() + FLAGS_ms;
1178                 do {
1179                     samples.push_back(time(loops, bench, target) / loops);
1180                 } while (now_ms() < stop);
1181             } else {
1182                 samples.reset(FLAGS_samples);
1183                 for (int s = 0; s < FLAGS_samples; s++) {
1184                     samples[s] = time(loops, bench, target) / loops;
1185                 }
1186             }
1187
1188 #if SK_SUPPORT_GPU
1189             SkTArray<SkString> keys;
1190             SkTArray<double> values;
1191             bool gpuStatsDump = FLAGS_gpuStatsDump && Benchmark::kGPU_Backend == configs[i].backend;
1192             if (gpuStatsDump) {
1193                 // TODO cache stats
1194                 bench->getGpuStats(canvas, &keys, &values);
1195             }
1196 #endif
1197
1198             bench->perCanvasPostDraw(canvas);
1199
1200             if (Benchmark::kNonRendering_Backend != target->config.backend &&
1201                 !FLAGS_writePath.isEmpty() && FLAGS_writePath[0]) {
1202                 SkString pngFilename = SkOSPath::Join(FLAGS_writePath[0], config);
1203                 pngFilename = SkOSPath::Join(pngFilename.c_str(), bench->getUniqueName());
1204                 pngFilename.append(".png");
1205                 write_canvas_png(target, pngFilename);
1206             }
1207
1208             if (kFailedLoops == loops) {
1209                 // Can't be timed.  A warning note has already been printed.
1210                 cleanup_run(target);
1211                 continue;
1212             }
1213
1214             Stats stats(samples);
1215             log->config(config);
1216             log->configOption("name", bench->getName());
1217             benchStream.fillCurrentOptions(log.get());
1218             target->fillOptions(log.get());
1219             log->metric("min_ms",    stats.min);
1220 #if SK_SUPPORT_GPU
1221             if (gpuStatsDump) {
1222                 // dump to json, only SKPBench currently returns valid keys / values
1223                 SkASSERT(keys.count() == values.count());
1224                 for (int i = 0; i < keys.count(); i++) {
1225                     log->metric(keys[i].c_str(), values[i]);
1226                 }
1227             }
1228 #endif
1229
1230             if (runs++ % FLAGS_flushEvery == 0) {
1231                 log->flush();
1232             }
1233
1234             if (kAutoTuneLoops != FLAGS_loops) {
1235                 if (configs.count() == 1) {
1236                     config = ""; // Only print the config if we run the same bench on more than one.
1237                 }
1238                 SkDebugf("%4d/%-4dMB\t%s\t%s\n"
1239                          , sk_tools::getCurrResidentSetSizeMB()
1240                          , sk_tools::getMaxResidentSetSizeMB()
1241                          , bench->getUniqueName()
1242                          , config);
1243             } else if (FLAGS_quiet) {
1244                 if (configs.count() == 1) {
1245                     config = ""; // Only print the config if we run the same bench on more than one.
1246                 }
1247                 SkDebugf("%s\t%s\t%s\n", HUMANIZE(stats.median), bench->getUniqueName(), config);
1248             } else {
1249                 const double stddev_percent = 100 * sqrt(stats.var) / stats.mean;
1250                 SkDebugf("%4d/%-4dMB\t%d\t%s\t%s\t%s\t%s\t%.0f%%\t%s\t%s\t%s\n"
1251                         , sk_tools::getCurrResidentSetSizeMB()
1252                         , sk_tools::getMaxResidentSetSizeMB()
1253                         , loops
1254                         , HUMANIZE(stats.min)
1255                         , HUMANIZE(stats.median)
1256                         , HUMANIZE(stats.mean)
1257                         , HUMANIZE(stats.max)
1258                         , stddev_percent
1259                         , FLAGS_ms ? to_string(samples.count()).c_str() : stats.plot.c_str()
1260                         , config
1261                         , bench->getUniqueName()
1262                         );
1263             }
1264
1265 #if SK_SUPPORT_GPU
1266             if (FLAGS_gpuStats && Benchmark::kGPU_Backend == configs[i].backend) {
1267                 gGrFactory->get(configs[i].ctxType)->printCacheStats();
1268                 gGrFactory->get(configs[i].ctxType)->printGpuStats();
1269             }
1270 #endif
1271
1272             if (FLAGS_verbose) {
1273                 SkDebugf("Samples:  ");
1274                 for (int i = 0; i < samples.count(); i++) {
1275                     SkDebugf("%s  ", HUMANIZE(samples[i]));
1276                 }
1277                 SkDebugf("%s\n", bench->getUniqueName());
1278             }
1279             cleanup_run(target);
1280         }
1281     }
1282
1283     log->bench("memory_usage", 0,0);
1284     log->config("meta");
1285     log->metric("max_rss_mb", sk_tools::getMaxResidentSetSizeMB());
1286
1287 #if SK_SUPPORT_GPU
1288     // Make sure we clean up the global GrContextFactory here, otherwise we might race with the
1289     // SkEventTracer destructor
1290     gGrFactory.reset(nullptr);
1291 #endif
1292
1293     return 0;
1294 }
1295
1296 #if !defined SK_BUILD_FOR_IOS
1297 int main(int argc, char** argv) {
1298     SkCommandLineFlags::Parse(argc, argv);
1299     return nanobench_main();
1300 }
1301 #endif