• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "bench/nanobench.h"
11 
12 #include "bench/AndroidCodecBench.h"
13 #include "bench/Benchmark.h"
14 #include "bench/BitmapRegionDecoderBench.h"
15 #include "bench/CodecBench.h"
16 #include "bench/CodecBenchPriv.h"
17 #include "bench/GMBench.h"
18 #include "bench/RecordingBench.h"
19 #include "bench/ResultsWriter.h"
20 #include "bench/SKPAnimationBench.h"
21 #include "bench/SKPBench.h"
22 #include "include/android/SkBitmapRegionDecoder.h"
23 #include "include/codec/SkAndroidCodec.h"
24 #include "include/codec/SkCodec.h"
25 #include "include/core/SkCanvas.h"
26 #include "include/core/SkData.h"
27 #include "include/core/SkGraphics.h"
28 #include "include/core/SkPictureRecorder.h"
29 #include "include/core/SkString.h"
30 #include "include/core/SkSurface.h"
31 #include "include/core/SkTime.h"
32 #include "src/core/SkAutoMalloc.h"
33 #include "src/core/SkBBoxHierarchy.h"
34 #include "src/core/SkColorSpacePriv.h"
35 #include "src/core/SkLeanWindows.h"
36 #include "src/core/SkOSFile.h"
37 #include "src/core/SkTaskGroup.h"
38 #include "src/core/SkTraceEvent.h"
39 #include "src/utils/SkJSONWriter.h"
40 #include "src/utils/SkOSPath.h"
41 #include "tools/AutoreleasePool.h"
42 #include "tools/CrashHandler.h"
43 #include "tools/ProcStats.h"
44 #include "tools/Stats.h"
45 #include "tools/flags/CommonFlags.h"
46 #include "tools/flags/CommonFlagsConfig.h"
47 #include "tools/ios_utils.h"
48 #include "tools/trace/EventTracingPriv.h"
49 #include "tools/trace/SkDebugfTracer.h"
50 
51 #ifdef SK_XML
52 #include "experimental/svg/model/SkSVGDOM.h"
53 #endif  // SK_XML
54 
55 #include <stdlib.h>
56 #include <thread>
57 
58 extern bool gSkForceRasterPipelineBlitter;
59 
60 #ifndef SK_BUILD_FOR_WIN
61     #include <unistd.h>
62 
63 #endif
64 
65 #include "src/gpu/GrCaps.h"
66 #include "src/gpu/GrContextPriv.h"
67 #include "src/gpu/SkGr.h"
68 #include "src/gpu/gl/GrGLDefines.h"
69 #include "src/gpu/gl/GrGLGpu.h"
70 #include "src/gpu/gl/GrGLUtil.h"
71 #include "tools/gpu/GrContextFactory.h"
72 
73 using sk_gpu_test::ContextInfo;
74 using sk_gpu_test::GrContextFactory;
75 using sk_gpu_test::TestContext;
76 
77 GrContextOptions grContextOpts;
78 
79 static const int kAutoTuneLoops = 0;
80 
loops_help_txt()81 static SkString loops_help_txt() {
82     SkString help;
83     help.printf("Number of times to run each bench. Set this to %d to auto-"
84                 "tune for each bench. Timings are only reported when auto-tuning.",
85                 kAutoTuneLoops);
86     return help;
87 }
88 
to_string(int n)89 static SkString to_string(int n) {
90     SkString str;
91     str.appendS32(n);
92     return str;
93 }
94 
95 static DEFINE_int(loops, kAutoTuneLoops, loops_help_txt().c_str());
96 
97 static DEFINE_int(samples, 10, "Number of samples to measure for each bench.");
98 static DEFINE_int(ms, 0, "If >0, run each bench for this many ms instead of obeying --samples.");
99 static DEFINE_int(overheadLoops, 100000, "Loops to estimate timer overhead.");
100 static DEFINE_double(overheadGoal, 0.0001,
101               "Loop until timer overhead is at most this fraction of our measurments.");
102 static DEFINE_double(gpuMs, 5, "Target bench time in millseconds for GPU.");
103 static DEFINE_int(gpuFrameLag, 5,
104                     "If unknown, estimated maximum number of frames GPU allows to lag.");
105 
106 static DEFINE_string(outResultsFile, "", "If given, write results here as JSON.");
107 static DEFINE_int(maxCalibrationAttempts, 3,
108              "Try up to this many times to guess loops for a bench, or skip the bench.");
109 static DEFINE_int(maxLoops, 1000000, "Never run a bench more times than this.");
110 static DEFINE_string(clip, "0,0,1000,1000", "Clip for SKPs.");
111 static DEFINE_string(scales, "1.0", "Space-separated scales for SKPs.");
112 static DEFINE_string(zoom, "1.0,0",
113                      "Comma-separated zoomMax,zoomPeriodMs factors for a periodic SKP zoom "
114                      "function that ping-pongs between 1.0 and zoomMax.");
115 static DEFINE_bool(bbh, true, "Build a BBH for SKPs?");
116 static DEFINE_bool(mpd, true, "Use MultiPictureDraw for the SKPs?");
117 static DEFINE_bool(loopSKP, true, "Loop SKPs like we do for micro benches?");
118 static DEFINE_int(flushEvery, 10, "Flush --outResultsFile every Nth run.");
119 static DEFINE_bool(gpuStats, false, "Print GPU stats after each gpu benchmark?");
120 static DEFINE_bool(gpuStatsDump, false, "Dump GPU states after each benchmark to json");
121 static DEFINE_bool(keepAlive, false, "Print a message every so often so that we don't time out");
122 static DEFINE_bool(csv, false, "Print status in CSV format");
123 static DEFINE_string(sourceType, "",
124         "Apply usual --match rules to source type: bench, gm, skp, image, etc.");
125 static DEFINE_string(benchType,  "",
126         "Apply usual --match rules to bench type: micro, recording, "
127         "piping, playback, skcodec, etc.");
128 
129 static DEFINE_bool(forceRasterPipeline, false, "sets gSkForceRasterPipelineBlitter");
130 
131 static DEFINE_bool2(pre_log, p, false,
132                     "Log before running each test. May be incomprehensible when threading");
133 
134 static DEFINE_bool(cpu, true, "master switch for running CPU-bound work.");
135 static DEFINE_bool(gpu, true, "master switch for running GPU-bound work.");
136 static DEFINE_bool(dryRun, false,
137                    "just print the tests that would be run, without actually running them.");
138 static DEFINE_string(images, "",
139                      "List of images and/or directories to decode. A directory with no images"
140                      " is treated as a fatal error.");
141 static DEFINE_bool(simpleCodec, false,
142                    "Runs of a subset of the codec tests, always N32, Premul or Opaque");
143 
144 static DEFINE_string2(match, m, nullptr,
145                "[~][^]substring[$] [...] of name to run.\n"
146                "Multiple matches may be separated by spaces.\n"
147                "~ causes a matching name to always be skipped\n"
148                "^ requires the start of the name to match\n"
149                "$ requires the end of the name to match\n"
150                "^ and $ requires an exact match\n"
151                "If a name does not match any list entry,\n"
152                "it is skipped unless some list entry starts with ~");
153 
154 static DEFINE_bool2(quiet, q, false, "if true, don't print status updates.");
155 static DEFINE_bool2(verbose, v, false, "enable verbose output from the test driver.");
156 
157 
158 static DEFINE_string(skps, "skps", "Directory to read skps from.");
159 static DEFINE_string(svgs, "", "Directory to read SVGs from, or a single SVG file.");
160 
161 static DEFINE_int_2(threads, j, -1,
162                "Run threadsafe tests on a threadpool with this many extra threads, "
163                "defaulting to one extra thread per core.");
164 
165 static DEFINE_string2(writePath, w, "", "If set, write bitmaps here as .pngs.");
166 
167 static DEFINE_string(key, "",
168                      "Space-separated key/value pairs to add to JSON identifying this builder.");
169 static DEFINE_string(properties, "",
170                      "Space-separated key/value pairs to add to JSON identifying this run.");
171 
172 static DEFINE_bool(purgeBetweenBenches, false,
173                    "Call SkGraphics::PurgeAllCaches() between each benchmark?");
174 
now_ms()175 static double now_ms() { return SkTime::GetNSecs() * 1e-6; }
176 
humanize(double ms)177 static SkString humanize(double ms) {
178     if (FLAGS_verbose) return SkStringPrintf("%llu", (uint64_t)(ms*1e6));
179     return HumanizeMs(ms);
180 }
181 #define HUMANIZE(ms) humanize(ms).c_str()
182 
init(SkImageInfo info,Benchmark * bench)183 bool Target::init(SkImageInfo info, Benchmark* bench) {
184     if (Benchmark::kRaster_Backend == config.backend) {
185         this->surface = SkSurface::MakeRaster(info);
186         if (!this->surface) {
187             return false;
188         }
189     }
190     return true;
191 }
capturePixels(SkBitmap * bmp)192 bool Target::capturePixels(SkBitmap* bmp) {
193     SkCanvas* canvas = this->getCanvas();
194     if (!canvas) {
195         return false;
196     }
197     bmp->allocPixels(canvas->imageInfo());
198     if (!canvas->readPixels(*bmp, 0, 0)) {
199         SkDebugf("Can't read canvas pixels.\n");
200         return false;
201     }
202     return true;
203 }
204 
205 struct GPUTarget : public Target {
GPUTargetGPUTarget206     explicit GPUTarget(const Config& c) : Target(c) {}
207     ContextInfo contextInfo;
208     std::unique_ptr<GrContextFactory> factory;
209 
setupGPUTarget210     void setup() override {
211         this->contextInfo.testContext()->makeCurrent();
212         // Make sure we're done with whatever came before.
213         this->contextInfo.testContext()->finish();
214     }
endTimingGPUTarget215     void endTiming() override {
216         if (this->contextInfo.testContext()) {
217             this->contextInfo.testContext()->waitOnSyncOrSwap();
218         }
219     }
fenceGPUTarget220     void fence() override { this->contextInfo.testContext()->finish(); }
221 
needsFrameTimingGPUTarget222     bool needsFrameTiming(int* maxFrameLag) const override {
223         if (!this->contextInfo.testContext()->getMaxGpuFrameLag(maxFrameLag)) {
224             // Frame lag is unknown.
225             *maxFrameLag = FLAGS_gpuFrameLag;
226         }
227         return true;
228     }
initGPUTarget229     bool init(SkImageInfo info, Benchmark* bench) override {
230         GrContextOptions options = grContextOpts;
231         bench->modifyGrContextOptions(&options);
232         this->factory.reset(new GrContextFactory(options));
233         uint32_t flags = this->config.useDFText ? SkSurfaceProps::kUseDeviceIndependentFonts_Flag :
234                                                   0;
235         SkSurfaceProps props(flags, SkSurfaceProps::kLegacyFontHost_InitType);
236         this->surface = SkSurface::MakeRenderTarget(
237                 this->factory->get(this->config.ctxType, this->config.ctxOverrides),
238                 SkBudgeted::kNo, info, this->config.samples, &props);
239         this->contextInfo =
240                 this->factory->getContextInfo(this->config.ctxType, this->config.ctxOverrides);
241         if (!this->surface.get()) {
242             return false;
243         }
244         if (!this->contextInfo.testContext()->fenceSyncSupport()) {
245             SkDebugf("WARNING: GL context for config \"%s\" does not support fence sync. "
246                      "Timings might not be accurate.\n", this->config.name.c_str());
247         }
248         return true;
249     }
fillOptionsGPUTarget250     void fillOptions(NanoJSONResultsWriter& log) override {
251         const GrGLubyte* version;
252         if (this->contextInfo.backend() == GrBackendApi::kOpenGL) {
253             const GrGLInterface* gl =
254                     static_cast<GrGLGpu*>(this->contextInfo.grContext()->priv().getGpu())
255                             ->glInterface();
256             GR_GL_CALL_RET(gl, version, GetString(GR_GL_VERSION));
257             log.appendString("GL_VERSION", (const char*)(version));
258 
259             GR_GL_CALL_RET(gl, version, GetString(GR_GL_RENDERER));
260             log.appendString("GL_RENDERER", (const char*) version);
261 
262             GR_GL_CALL_RET(gl, version, GetString(GR_GL_VENDOR));
263             log.appendString("GL_VENDOR", (const char*) version);
264 
265             GR_GL_CALL_RET(gl, version, GetString(GR_GL_SHADING_LANGUAGE_VERSION));
266             log.appendString("GL_SHADING_LANGUAGE_VERSION", (const char*) version);
267         }
268     }
269 
dumpStatsGPUTarget270     void dumpStats() override {
271         this->contextInfo.grContext()->priv().printCacheStats();
272         this->contextInfo.grContext()->priv().printGpuStats();
273     }
274 };
275 
time(int loops,Benchmark * bench,Target * target)276 static double time(int loops, Benchmark* bench, Target* target) {
277     SkCanvas* canvas = target->getCanvas();
278     if (canvas) {
279         canvas->clear(SK_ColorWHITE);
280     }
281     bench->preDraw(canvas);
282     double start = now_ms();
283     canvas = target->beginTiming(canvas);
284     bench->draw(loops, canvas);
285     if (canvas) {
286         canvas->flush();
287     }
288     target->endTiming();
289     double elapsed = now_ms() - start;
290     bench->postDraw(canvas);
291     return elapsed;
292 }
293 
estimate_timer_overhead()294 static double estimate_timer_overhead() {
295     double overhead = 0;
296     for (int i = 0; i < FLAGS_overheadLoops; i++) {
297         double start = now_ms();
298         overhead += now_ms() - start;
299     }
300     return overhead / FLAGS_overheadLoops;
301 }
302 
detect_forever_loops(int loops)303 static int detect_forever_loops(int loops) {
304     // look for a magic run-forever value
305     if (loops < 0) {
306         loops = SK_MaxS32;
307     }
308     return loops;
309 }
310 
clamp_loops(int loops)311 static int clamp_loops(int loops) {
312     if (loops < 1) {
313         SkDebugf("ERROR: clamping loops from %d to 1. "
314                  "There's probably something wrong with the bench.\n", loops);
315         return 1;
316     }
317     if (loops > FLAGS_maxLoops) {
318         SkDebugf("WARNING: clamping loops from %d to FLAGS_maxLoops, %d.\n", loops, FLAGS_maxLoops);
319         return FLAGS_maxLoops;
320     }
321     return loops;
322 }
323 
write_canvas_png(Target * target,const SkString & filename)324 static bool write_canvas_png(Target* target, const SkString& filename) {
325 
326     if (filename.isEmpty()) {
327         return false;
328     }
329     if (target->getCanvas() &&
330         kUnknown_SkColorType == target->getCanvas()->imageInfo().colorType()) {
331         return false;
332     }
333 
334     SkBitmap bmp;
335 
336     if (!target->capturePixels(&bmp)) {
337         return false;
338     }
339 
340     SkString dir = SkOSPath::Dirname(filename.c_str());
341     if (!sk_mkdir(dir.c_str())) {
342         SkDebugf("Can't make dir %s.\n", dir.c_str());
343         return false;
344     }
345     SkFILEWStream stream(filename.c_str());
346     if (!stream.isValid()) {
347         SkDebugf("Can't write %s.\n", filename.c_str());
348         return false;
349     }
350     if (!SkEncodeImage(&stream, bmp, SkEncodedImageFormat::kPNG, 100)) {
351         SkDebugf("Can't encode a PNG.\n");
352         return false;
353     }
354     return true;
355 }
356 
357 static int kFailedLoops = -2;
setup_cpu_bench(const double overhead,Target * target,Benchmark * bench)358 static int setup_cpu_bench(const double overhead, Target* target, Benchmark* bench) {
359     // First figure out approximately how many loops of bench it takes to make overhead negligible.
360     double bench_plus_overhead = 0.0;
361     int round = 0;
362     int loops = bench->calculateLoops(FLAGS_loops);
363     if (kAutoTuneLoops == loops) {
364         while (bench_plus_overhead < overhead) {
365             if (round++ == FLAGS_maxCalibrationAttempts) {
366                 SkDebugf("WARNING: Can't estimate loops for %s (%s vs. %s); skipping.\n",
367                          bench->getUniqueName(), HUMANIZE(bench_plus_overhead), HUMANIZE(overhead));
368                 return kFailedLoops;
369             }
370             bench_plus_overhead = time(1, bench, target);
371         }
372     }
373 
374     // Later we'll just start and stop the timer once but loop N times.
375     // We'll pick N to make timer overhead negligible:
376     //
377     //          overhead
378     //  -------------------------  < FLAGS_overheadGoal
379     //  overhead + N * Bench Time
380     //
381     // where bench_plus_overhead ~=~ overhead + Bench Time.
382     //
383     // Doing some math, we get:
384     //
385     //  (overhead / FLAGS_overheadGoal) - overhead
386     //  ------------------------------------------  < N
387     //       bench_plus_overhead - overhead)
388     //
389     // Luckily, this also works well in practice. :)
390     if (kAutoTuneLoops == loops) {
391         const double numer = overhead / FLAGS_overheadGoal - overhead;
392         const double denom = bench_plus_overhead - overhead;
393         loops = (int)ceil(numer / denom);
394         loops = clamp_loops(loops);
395     } else {
396         loops = detect_forever_loops(loops);
397     }
398 
399     return loops;
400 }
401 
setup_gpu_bench(Target * target,Benchmark * bench,int maxGpuFrameLag)402 static int setup_gpu_bench(Target* target, Benchmark* bench, int maxGpuFrameLag) {
403     // First, figure out how many loops it'll take to get a frame up to FLAGS_gpuMs.
404     int loops = bench->calculateLoops(FLAGS_loops);
405     if (kAutoTuneLoops == loops) {
406         loops = 1;
407         double elapsed = 0;
408         do {
409             if (1<<30 == loops) {
410                 // We're about to wrap.  Something's wrong with the bench.
411                 loops = 0;
412                 break;
413             }
414             loops *= 2;
415             // If the GPU lets frames lag at all, we need to make sure we're timing
416             // _this_ round, not still timing last round.
417             for (int i = 0; i < maxGpuFrameLag; i++) {
418                 elapsed = time(loops, bench, target);
419             }
420         } while (elapsed < FLAGS_gpuMs);
421 
422         // We've overshot at least a little.  Scale back linearly.
423         loops = (int)ceil(loops * FLAGS_gpuMs / elapsed);
424         loops = clamp_loops(loops);
425 
426         // Make sure we're not still timing our calibration.
427         target->fence();
428     } else {
429         loops = detect_forever_loops(loops);
430     }
431     // Pretty much the same deal as the calibration: do some warmup to make
432     // sure we're timing steady-state pipelined frames.
433     for (int i = 0; i < maxGpuFrameLag; i++) {
434         time(loops, bench, target);
435     }
436 
437     return loops;
438 }
439 
440 #define kBogusContextType GrContextFactory::kGL_ContextType
441 #define kBogusContextOverrides GrContextFactory::ContextOverrides::kNone
442 
create_config(const SkCommandLineConfig * config,SkTArray<Config> * configs)443 static void create_config(const SkCommandLineConfig* config, SkTArray<Config>* configs) {
444     if (const auto* gpuConfig = config->asConfigGpu()) {
445         if (!FLAGS_gpu) {
446             SkDebugf("Skipping config '%s' as requested.\n", config->getTag().c_str());
447             return;
448         }
449 
450         const auto ctxType = gpuConfig->getContextType();
451         const auto ctxOverrides = gpuConfig->getContextOverrides();
452         const auto sampleCount = gpuConfig->getSamples();
453         const auto colorType = gpuConfig->getColorType();
454         auto colorSpace = gpuConfig->getColorSpace();
455         if (gpuConfig->getSurfType() != SkCommandLineConfigGpu::SurfType::kDefault) {
456             SkDebugf("This tool only supports the default surface type.");
457             return;
458         }
459 
460         GrContextFactory factory(grContextOpts);
461         if (const GrContext* ctx = factory.get(ctxType, ctxOverrides)) {
462             GrBackendFormat format = ctx->defaultBackendFormat(colorType, GrRenderable::kYes);
463             int supportedSampleCount =
464                     ctx->priv().caps()->getRenderTargetSampleCount(sampleCount, format);
465             if (sampleCount != supportedSampleCount) {
466                 SkDebugf("Configuration '%s' sample count %d is not a supported sample count.\n",
467                          config->getTag().c_str(), sampleCount);
468                 return;
469             }
470         } else {
471             SkDebugf("No context was available matching config '%s'.\n",
472                      config->getTag().c_str());
473             return;
474         }
475 
476         Config target = {
477             gpuConfig->getTag(),
478             Benchmark::kGPU_Backend,
479             colorType,
480             kPremul_SkAlphaType,
481             sk_ref_sp(colorSpace),
482             sampleCount,
483             ctxType,
484             ctxOverrides,
485             gpuConfig->getUseDIText()
486         };
487 
488         configs->push_back(target);
489         return;
490     }
491 
492     #define CPU_CONFIG(name, backend, color, alpha, colorSpace)                \
493         if (config->getTag().equals(#name)) {                                  \
494             if (!FLAGS_cpu) {                                                  \
495                 SkDebugf("Skipping config '%s' as requested.\n",               \
496                          config->getTag().c_str());                            \
497                 return;                                                        \
498             }                                                                  \
499             Config config = {                                                  \
500                 SkString(#name), Benchmark::backend, color, alpha, colorSpace, \
501                 0, kBogusContextType, kBogusContextOverrides, false            \
502             };                                                                 \
503             configs->push_back(config);                                        \
504             return;                                                            \
505         }
506 
507     CPU_CONFIG(nonrendering, kNonRendering_Backend,
508                kUnknown_SkColorType, kUnpremul_SkAlphaType, nullptr)
509 
510     CPU_CONFIG(a8,   kRaster_Backend, kAlpha_8_SkColorType, kPremul_SkAlphaType, nullptr)
511     CPU_CONFIG(8888, kRaster_Backend,     kN32_SkColorType, kPremul_SkAlphaType, nullptr)
512     CPU_CONFIG(565,  kRaster_Backend, kRGB_565_SkColorType, kOpaque_SkAlphaType, nullptr)
513 
514     // 'narrow' has a gamut narrower than sRGB, and different transfer function.
515     auto narrow = SkColorSpace::MakeRGB(SkNamedTransferFn::k2Dot2, gNarrow_toXYZD50),
516            srgb = SkColorSpace::MakeSRGB(),
517      srgbLinear = SkColorSpace::MakeSRGBLinear();
518 
519     CPU_CONFIG(    f16, kRaster_Backend,  kRGBA_F16_SkColorType, kPremul_SkAlphaType, srgbLinear)
520     CPU_CONFIG(   srgb, kRaster_Backend, kRGBA_8888_SkColorType, kPremul_SkAlphaType, srgb      )
521     CPU_CONFIG(  esrgb, kRaster_Backend,  kRGBA_F16_SkColorType, kPremul_SkAlphaType, srgb      )
522     CPU_CONFIG( narrow, kRaster_Backend, kRGBA_8888_SkColorType, kPremul_SkAlphaType, narrow    )
523     CPU_CONFIG(enarrow, kRaster_Backend,  kRGBA_F16_SkColorType, kPremul_SkAlphaType, narrow    )
524 
525     #undef CPU_CONFIG
526 
527     SkDebugf("Unknown config '%s'.\n", config->getTag().c_str());
528 }
529 
530 // Append all configs that are enabled and supported.
create_configs(SkTArray<Config> * configs)531 void create_configs(SkTArray<Config>* configs) {
532     SkCommandLineConfigArray array;
533     ParseConfigs(FLAGS_config, &array);
534     for (int i = 0; i < array.count(); ++i) {
535         create_config(array[i].get(), configs);
536     }
537 
538     // If no just default configs were requested, then we're okay.
539     if (array.count() == 0 || FLAGS_config.count() == 0 ||
540         // Otherwise, make sure that all specified configs have been created.
541         array.count() == configs->count()) {
542         return;
543     }
544     exit(1);
545 }
546 
547 // disable warning : switch statement contains default but no 'case' labels
548 #if defined _WIN32
549 #pragma warning ( push )
550 #pragma warning ( disable : 4065 )
551 #endif
552 
553 // If bench is enabled for config, returns a Target* for it, otherwise nullptr.
is_enabled(Benchmark * bench,const Config & config)554 static Target* is_enabled(Benchmark* bench, const Config& config) {
555     if (!bench->isSuitableFor(config.backend)) {
556         return nullptr;
557     }
558 
559     SkImageInfo info = SkImageInfo::Make(bench->getSize().fX, bench->getSize().fY,
560                                          config.color, config.alpha, config.colorSpace);
561 
562     Target* target = nullptr;
563 
564     switch (config.backend) {
565     case Benchmark::kGPU_Backend:
566         target = new GPUTarget(config);
567         break;
568     default:
569         target = new Target(config);
570         break;
571     }
572 
573     if (!target->init(info, bench)) {
574         delete target;
575         return nullptr;
576     }
577     return target;
578 }
579 
580 #if defined _WIN32
581 #pragma warning ( pop )
582 #endif
583 
valid_brd_bench(sk_sp<SkData> encoded,SkColorType colorType,uint32_t sampleSize,uint32_t minOutputSize,int * width,int * height)584 static bool valid_brd_bench(sk_sp<SkData> encoded, SkColorType colorType, uint32_t sampleSize,
585         uint32_t minOutputSize, int* width, int* height) {
586     std::unique_ptr<SkBitmapRegionDecoder> brd(
587             SkBitmapRegionDecoder::Create(encoded, SkBitmapRegionDecoder::kAndroidCodec_Strategy));
588     if (nullptr == brd.get()) {
589         // This is indicates that subset decoding is not supported for a particular image format.
590         return false;
591     }
592 
593     if (sampleSize * minOutputSize > (uint32_t) brd->width() || sampleSize * minOutputSize >
594             (uint32_t) brd->height()) {
595         // This indicates that the image is not large enough to decode a
596         // minOutputSize x minOutputSize subset at the given sampleSize.
597         return false;
598     }
599 
600     // Set the image width and height.  The calling code will use this to choose subsets to decode.
601     *width = brd->width();
602     *height = brd->height();
603     return true;
604 }
605 
cleanup_run(Target * target)606 static void cleanup_run(Target* target) {
607     delete target;
608 }
609 
collect_files(const CommandLineFlags::StringArray & paths,const char * ext,SkTArray<SkString> * list)610 static void collect_files(const CommandLineFlags::StringArray& paths,
611                           const char*                          ext,
612                           SkTArray<SkString>*                  list) {
613     for (int i = 0; i < paths.count(); ++i) {
614         if (SkStrEndsWith(paths[i], ext)) {
615             list->push_back(SkString(paths[i]));
616         } else {
617             SkOSFile::Iter it(paths[i], ext);
618             SkString path;
619             while (it.next(&path)) {
620                 list->push_back(SkOSPath::Join(paths[i], path.c_str()));
621             }
622         }
623     }
624 }
625 
626 class BenchmarkStream {
627 public:
BenchmarkStream()628     BenchmarkStream() : fBenches(BenchRegistry::Head())
629                       , fGMs(skiagm::GMRegistry::Head())
630                       , fCurrentRecording(0)
631                       , fCurrentDeserialPicture(0)
632                       , fCurrentScale(0)
633                       , fCurrentSKP(0)
634                       , fCurrentSVG(0)
635                       , fCurrentUseMPD(0)
636                       , fCurrentCodec(0)
637                       , fCurrentAndroidCodec(0)
638                       , fCurrentBRDImage(0)
639                       , fCurrentColorType(0)
640                       , fCurrentAlphaType(0)
641                       , fCurrentSubsetType(0)
642                       , fCurrentSampleSize(0)
643                       , fCurrentAnimSKP(0) {
644         collect_files(FLAGS_skps, ".skp", &fSKPs);
645         collect_files(FLAGS_svgs, ".svg", &fSVGs);
646 
647         if (4 != sscanf(FLAGS_clip[0], "%d,%d,%d,%d",
648                         &fClip.fLeft, &fClip.fTop, &fClip.fRight, &fClip.fBottom)) {
649             SkDebugf("Can't parse %s from --clip as an SkIRect.\n", FLAGS_clip[0]);
650             exit(1);
651         }
652 
653         for (int i = 0; i < FLAGS_scales.count(); i++) {
654             if (1 != sscanf(FLAGS_scales[i], "%f", &fScales.push_back())) {
655                 SkDebugf("Can't parse %s from --scales as an SkScalar.\n", FLAGS_scales[i]);
656                 exit(1);
657             }
658         }
659 
660         if (2 != sscanf(FLAGS_zoom[0], "%f,%lf", &fZoomMax, &fZoomPeriodMs)) {
661             SkDebugf("Can't parse %s from --zoom as a zoomMax,zoomPeriodMs.\n", FLAGS_zoom[0]);
662             exit(1);
663         }
664 
665         if (FLAGS_mpd) {
666             fUseMPDs.push_back() = true;
667         }
668         fUseMPDs.push_back() = false;
669 
670         // Prepare the images for decoding
671         if (!CollectImages(FLAGS_images, &fImages)) {
672             exit(1);
673         }
674 
675         // Choose the candidate color types for image decoding
676         fColorTypes.push_back(kN32_SkColorType);
677         if (!FLAGS_simpleCodec) {
678             fColorTypes.push_back(kRGB_565_SkColorType);
679             fColorTypes.push_back(kAlpha_8_SkColorType);
680             fColorTypes.push_back(kGray_8_SkColorType);
681         }
682     }
683 
ReadPicture(const char * path)684     static sk_sp<SkPicture> ReadPicture(const char* path) {
685         // Not strictly necessary, as it will be checked again later,
686         // but helps to avoid a lot of pointless work if we're going to skip it.
687         if (CommandLineFlags::ShouldSkip(FLAGS_match, SkOSPath::Basename(path).c_str())) {
688             return nullptr;
689         }
690 
691         std::unique_ptr<SkStream> stream = SkStream::MakeFromFile(path);
692         if (!stream) {
693             SkDebugf("Could not read %s.\n", path);
694             return nullptr;
695         }
696 
697         return SkPicture::MakeFromStream(stream.get());
698     }
699 
ReadSVGPicture(const char * path)700     static sk_sp<SkPicture> ReadSVGPicture(const char* path) {
701         sk_sp<SkData> data(SkData::MakeFromFileName(path));
702         if (!data) {
703             SkDebugf("Could not read %s.\n", path);
704             return nullptr;
705         }
706 
707 #ifdef SK_XML
708         SkMemoryStream stream(std::move(data));
709         sk_sp<SkSVGDOM> svgDom = SkSVGDOM::MakeFromStream(stream);
710         if (!svgDom) {
711             SkDebugf("Could not parse %s.\n", path);
712             return nullptr;
713         }
714 
715         // Use the intrinsic SVG size if available, otherwise fall back to a default value.
716         static const SkSize kDefaultContainerSize = SkSize::Make(128, 128);
717         if (svgDom->containerSize().isEmpty()) {
718             svgDom->setContainerSize(kDefaultContainerSize);
719         }
720 
721         SkPictureRecorder recorder;
722         svgDom->render(recorder.beginRecording(svgDom->containerSize().width(),
723                                                svgDom->containerSize().height()));
724         return recorder.finishRecordingAsPicture();
725 #else
726         return nullptr;
727 #endif  // SK_XML
728     }
729 
next()730     Benchmark* next() {
731         std::unique_ptr<Benchmark> bench;
732         do {
733             bench.reset(this->rawNext());
734             if (!bench) {
735                 return nullptr;
736             }
737         } while (CommandLineFlags::ShouldSkip(FLAGS_sourceType, fSourceType) ||
738                  CommandLineFlags::ShouldSkip(FLAGS_benchType, fBenchType));
739         return bench.release();
740     }
741 
rawNext()742     Benchmark* rawNext() {
743         if (fBenches) {
744             Benchmark* bench = fBenches->get()(nullptr);
745             fBenches = fBenches->next();
746             fSourceType = "bench";
747             fBenchType  = "micro";
748             return bench;
749         }
750 
751         while (fGMs) {
752             std::unique_ptr<skiagm::GM> gm = fGMs->get()();
753             fGMs = fGMs->next();
754             if (gm->runAsBench()) {
755                 fSourceType = "gm";
756                 fBenchType  = "micro";
757                 return new GMBench(std::move(gm));
758             }
759         }
760 
761         // First add all .skps as RecordingBenches.
762         while (fCurrentRecording < fSKPs.count()) {
763             const SkString& path = fSKPs[fCurrentRecording++];
764             sk_sp<SkPicture> pic = ReadPicture(path.c_str());
765             if (!pic) {
766                 continue;
767             }
768             SkString name = SkOSPath::Basename(path.c_str());
769             fSourceType = "skp";
770             fBenchType  = "recording";
771             fSKPBytes = static_cast<double>(pic->approximateBytesUsed());
772             fSKPOps   = pic->approximateOpCount();
773             return new RecordingBench(name.c_str(), pic.get(), FLAGS_bbh);
774         }
775 
776         // Add all .skps as DeserializePictureBenchs.
777         while (fCurrentDeserialPicture < fSKPs.count()) {
778             const SkString& path = fSKPs[fCurrentDeserialPicture++];
779             sk_sp<SkData> data = SkData::MakeFromFileName(path.c_str());
780             if (!data) {
781                 continue;
782             }
783             SkString name = SkOSPath::Basename(path.c_str());
784             fSourceType = "skp";
785             fBenchType  = "deserial";
786             fSKPBytes = static_cast<double>(data->size());
787             fSKPOps   = 0;
788             return new DeserializePictureBench(name.c_str(), std::move(data));
789         }
790 
791         // Then once each for each scale as SKPBenches (playback).
792         while (fCurrentScale < fScales.count()) {
793             while (fCurrentSKP < fSKPs.count()) {
794                 const SkString& path = fSKPs[fCurrentSKP];
795                 sk_sp<SkPicture> pic = ReadPicture(path.c_str());
796                 if (!pic) {
797                     fCurrentSKP++;
798                     continue;
799                 }
800 
801                 while (fCurrentUseMPD < fUseMPDs.count()) {
802                     if (FLAGS_bbh) {
803                         // The SKP we read off disk doesn't have a BBH.  Re-record so it grows one.
804                         SkRTreeFactory factory;
805                         SkPictureRecorder recorder;
806                         pic->playback(recorder.beginRecording(pic->cullRect().width(),
807                                                               pic->cullRect().height(),
808                                                               &factory,
809                                                               0));
810                         pic = recorder.finishRecordingAsPicture();
811                     }
812                     SkString name = SkOSPath::Basename(path.c_str());
813                     fSourceType = "skp";
814                     fBenchType = "playback";
815                     return new SKPBench(name.c_str(), pic.get(), fClip, fScales[fCurrentScale],
816                                         fUseMPDs[fCurrentUseMPD++], FLAGS_loopSKP);
817                 }
818                 fCurrentUseMPD = 0;
819                 fCurrentSKP++;
820             }
821 
822             while (fCurrentSVG++ < fSVGs.count()) {
823                 const char* path = fSVGs[fCurrentSVG - 1].c_str();
824                 if (sk_sp<SkPicture> pic = ReadSVGPicture(path)) {
825                     fSourceType = "svg";
826                     fBenchType = "playback";
827                     return new SKPBench(SkOSPath::Basename(path).c_str(), pic.get(), fClip,
828                                         fScales[fCurrentScale], false, FLAGS_loopSKP);
829                 }
830             }
831 
832             fCurrentSKP = 0;
833             fCurrentSVG = 0;
834             fCurrentScale++;
835         }
836 
837         // Now loop over each skp again if we have an animation
838         if (fZoomMax != 1.0f && fZoomPeriodMs > 0) {
839             while (fCurrentAnimSKP < fSKPs.count()) {
840                 const SkString& path = fSKPs[fCurrentAnimSKP];
841                 sk_sp<SkPicture> pic = ReadPicture(path.c_str());
842                 if (!pic) {
843                     fCurrentAnimSKP++;
844                     continue;
845                 }
846 
847                 fCurrentAnimSKP++;
848                 SkString name = SkOSPath::Basename(path.c_str());
849                 sk_sp<SKPAnimationBench::Animation> animation =
850                     SKPAnimationBench::MakeZoomAnimation(fZoomMax, fZoomPeriodMs);
851                 return new SKPAnimationBench(name.c_str(), pic.get(), fClip, std::move(animation),
852                                              FLAGS_loopSKP);
853             }
854         }
855 
856         for (; fCurrentCodec < fImages.count(); fCurrentCodec++) {
857             fSourceType = "image";
858             fBenchType = "skcodec";
859             const SkString& path = fImages[fCurrentCodec];
860             if (CommandLineFlags::ShouldSkip(FLAGS_match, path.c_str())) {
861                 continue;
862             }
863             sk_sp<SkData> encoded(SkData::MakeFromFileName(path.c_str()));
864             std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
865             if (!codec) {
866                 // Nothing to time.
867                 SkDebugf("Cannot find codec for %s\n", path.c_str());
868                 continue;
869             }
870 
871             while (fCurrentColorType < fColorTypes.count()) {
872                 const SkColorType colorType = fColorTypes[fCurrentColorType];
873 
874                 SkAlphaType alphaType = codec->getInfo().alphaType();
875                 if (FLAGS_simpleCodec) {
876                     if (kUnpremul_SkAlphaType == alphaType) {
877                         alphaType = kPremul_SkAlphaType;
878                     }
879 
880                     fCurrentColorType++;
881                 } else {
882                     switch (alphaType) {
883                         case kOpaque_SkAlphaType:
884                             // We only need to test one alpha type (opaque).
885                             fCurrentColorType++;
886                             break;
887                         case kUnpremul_SkAlphaType:
888                         case kPremul_SkAlphaType:
889                             if (0 == fCurrentAlphaType) {
890                                 // Test unpremul first.
891                                 alphaType = kUnpremul_SkAlphaType;
892                                 fCurrentAlphaType++;
893                             } else {
894                                 // Test premul.
895                                 alphaType = kPremul_SkAlphaType;
896                                 fCurrentAlphaType = 0;
897                                 fCurrentColorType++;
898                             }
899                             break;
900                         default:
901                             SkASSERT(false);
902                             fCurrentColorType++;
903                             break;
904                     }
905                 }
906 
907                 // Make sure we can decode to this color type and alpha type.
908                 SkImageInfo info =
909                         codec->getInfo().makeColorType(colorType).makeAlphaType(alphaType);
910                 const size_t rowBytes = info.minRowBytes();
911                 SkAutoMalloc storage(info.computeByteSize(rowBytes));
912 
913                 const SkCodec::Result result = codec->getPixels(
914                         info, storage.get(), rowBytes);
915                 switch (result) {
916                     case SkCodec::kSuccess:
917                     case SkCodec::kIncompleteInput:
918                         return new CodecBench(SkOSPath::Basename(path.c_str()),
919                                               encoded.get(), colorType, alphaType);
920                     case SkCodec::kInvalidConversion:
921                         // This is okay. Not all conversions are valid.
922                         break;
923                     default:
924                         // This represents some sort of failure.
925                         SkASSERT(false);
926                         break;
927                 }
928             }
929             fCurrentColorType = 0;
930         }
931 
932         // Run AndroidCodecBenches
933         const int sampleSizes[] = { 2, 4, 8 };
934         for (; fCurrentAndroidCodec < fImages.count(); fCurrentAndroidCodec++) {
935             fSourceType = "image";
936             fBenchType = "skandroidcodec";
937 
938             const SkString& path = fImages[fCurrentAndroidCodec];
939             if (CommandLineFlags::ShouldSkip(FLAGS_match, path.c_str())) {
940                 continue;
941             }
942             sk_sp<SkData> encoded(SkData::MakeFromFileName(path.c_str()));
943             std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(encoded));
944             if (!codec) {
945                 // Nothing to time.
946                 SkDebugf("Cannot find codec for %s\n", path.c_str());
947                 continue;
948             }
949 
950             while (fCurrentSampleSize < (int) SK_ARRAY_COUNT(sampleSizes)) {
951                 int sampleSize = sampleSizes[fCurrentSampleSize];
952                 fCurrentSampleSize++;
953                 if (10 * sampleSize > SkTMin(codec->getInfo().width(), codec->getInfo().height())) {
954                     // Avoid benchmarking scaled decodes of already small images.
955                     break;
956                 }
957 
958                 return new AndroidCodecBench(SkOSPath::Basename(path.c_str()),
959                                              encoded.get(), sampleSize);
960             }
961             fCurrentSampleSize = 0;
962         }
963 
964         // Run the BRDBenches
965         // We intend to create benchmarks that model the use cases in
966         // android/libraries/social/tiledimage.  In this library, an image is decoded in 512x512
967         // tiles.  The image can be translated freely, so the location of a tile may be anywhere in
968         // the image.  For that reason, we will benchmark decodes in five representative locations
969         // in the image.  Additionally, this use case utilizes power of two scaling, so we will
970         // test on power of two sample sizes.  The output tile is always 512x512, so, when a
971         // sampleSize is used, the size of the subset that is decoded is always
972         // (sampleSize*512)x(sampleSize*512).
973         // There are a few good reasons to only test on power of two sample sizes at this time:
974         //     All use cases we are aware of only scale by powers of two.
975         //     PNG decodes use the indicated sampling strategy regardless of the sample size, so
976         //         these tests are sufficient to provide good coverage of our scaling options.
977         const uint32_t brdSampleSizes[] = { 1, 2, 4, 8, 16 };
978         const uint32_t minOutputSize = 512;
979         for (; fCurrentBRDImage < fImages.count(); fCurrentBRDImage++) {
980             fSourceType = "image";
981             fBenchType = "BRD";
982 
983             const SkString& path = fImages[fCurrentBRDImage];
984             if (CommandLineFlags::ShouldSkip(FLAGS_match, path.c_str())) {
985                 continue;
986             }
987 
988             while (fCurrentColorType < fColorTypes.count()) {
989                 while (fCurrentSampleSize < (int) SK_ARRAY_COUNT(brdSampleSizes)) {
990                     while (fCurrentSubsetType <= kLastSingle_SubsetType) {
991 
992                         sk_sp<SkData> encoded(SkData::MakeFromFileName(path.c_str()));
993                         const SkColorType colorType = fColorTypes[fCurrentColorType];
994                         uint32_t sampleSize = brdSampleSizes[fCurrentSampleSize];
995                         int currentSubsetType = fCurrentSubsetType++;
996 
997                         int width = 0;
998                         int height = 0;
999                         if (!valid_brd_bench(encoded, colorType, sampleSize, minOutputSize,
1000                                 &width, &height)) {
1001                             break;
1002                         }
1003 
1004                         SkString basename = SkOSPath::Basename(path.c_str());
1005                         SkIRect subset;
1006                         const uint32_t subsetSize = sampleSize * minOutputSize;
1007                         switch (currentSubsetType) {
1008                             case kTopLeft_SubsetType:
1009                                 basename.append("_TopLeft");
1010                                 subset = SkIRect::MakeXYWH(0, 0, subsetSize, subsetSize);
1011                                 break;
1012                             case kTopRight_SubsetType:
1013                                 basename.append("_TopRight");
1014                                 subset = SkIRect::MakeXYWH(width - subsetSize, 0, subsetSize,
1015                                         subsetSize);
1016                                 break;
1017                             case kMiddle_SubsetType:
1018                                 basename.append("_Middle");
1019                                 subset = SkIRect::MakeXYWH((width - subsetSize) / 2,
1020                                         (height - subsetSize) / 2, subsetSize, subsetSize);
1021                                 break;
1022                             case kBottomLeft_SubsetType:
1023                                 basename.append("_BottomLeft");
1024                                 subset = SkIRect::MakeXYWH(0, height - subsetSize, subsetSize,
1025                                         subsetSize);
1026                                 break;
1027                             case kBottomRight_SubsetType:
1028                                 basename.append("_BottomRight");
1029                                 subset = SkIRect::MakeXYWH(width - subsetSize,
1030                                         height - subsetSize, subsetSize, subsetSize);
1031                                 break;
1032                             default:
1033                                 SkASSERT(false);
1034                         }
1035 
1036                         return new BitmapRegionDecoderBench(basename.c_str(), encoded.get(),
1037                                 colorType, sampleSize, subset);
1038                     }
1039                     fCurrentSubsetType = 0;
1040                     fCurrentSampleSize++;
1041                 }
1042                 fCurrentSampleSize = 0;
1043                 fCurrentColorType++;
1044             }
1045             fCurrentColorType = 0;
1046         }
1047 
1048         return nullptr;
1049     }
1050 
fillCurrentOptions(NanoJSONResultsWriter & log) const1051     void fillCurrentOptions(NanoJSONResultsWriter& log) const {
1052         log.appendString("source_type", fSourceType);
1053         log.appendString("bench_type",  fBenchType);
1054         if (0 == strcmp(fSourceType, "skp")) {
1055             log.appendString("clip",
1056                     SkStringPrintf("%d %d %d %d", fClip.fLeft, fClip.fTop,
1057                                                   fClip.fRight, fClip.fBottom).c_str());
1058             SkASSERT_RELEASE(fCurrentScale < fScales.count());  // debugging paranoia
1059             log.appendString("scale", SkStringPrintf("%.2g", fScales[fCurrentScale]).c_str());
1060             if (fCurrentUseMPD > 0) {
1061                 SkASSERT(1 == fCurrentUseMPD || 2 == fCurrentUseMPD);
1062                 log.appendString("multi_picture_draw",
1063                                  fUseMPDs[fCurrentUseMPD-1] ? "true" : "false");
1064             }
1065         }
1066     }
1067 
fillCurrentMetrics(NanoJSONResultsWriter & log) const1068     void fillCurrentMetrics(NanoJSONResultsWriter& log) const {
1069         if (0 == strcmp(fBenchType, "recording")) {
1070             log.appendMetric("bytes", fSKPBytes);
1071             log.appendMetric("ops", fSKPOps);
1072         }
1073     }
1074 
1075 private:
1076     enum SubsetType {
1077         kTopLeft_SubsetType     = 0,
1078         kTopRight_SubsetType    = 1,
1079         kMiddle_SubsetType      = 2,
1080         kBottomLeft_SubsetType  = 3,
1081         kBottomRight_SubsetType = 4,
1082         kTranslate_SubsetType   = 5,
1083         kZoom_SubsetType        = 6,
1084         kLast_SubsetType        = kZoom_SubsetType,
1085         kLastSingle_SubsetType  = kBottomRight_SubsetType,
1086     };
1087 
1088     const BenchRegistry* fBenches;
1089     const skiagm::GMRegistry* fGMs;
1090     SkIRect            fClip;
1091     SkTArray<SkScalar> fScales;
1092     SkTArray<SkString> fSKPs;
1093     SkTArray<SkString> fSVGs;
1094     SkTArray<bool>     fUseMPDs;
1095     SkTArray<SkString> fImages;
1096     SkTArray<SkColorType, true> fColorTypes;
1097     SkScalar           fZoomMax;
1098     double             fZoomPeriodMs;
1099 
1100     double fSKPBytes, fSKPOps;
1101 
1102     const char* fSourceType;  // What we're benching: bench, GM, SKP, ...
1103     const char* fBenchType;   // How we bench it: micro, recording, playback, ...
1104     int fCurrentRecording;
1105     int fCurrentDeserialPicture;
1106     int fCurrentScale;
1107     int fCurrentSKP;
1108     int fCurrentSVG;
1109     int fCurrentUseMPD;
1110     int fCurrentCodec;
1111     int fCurrentAndroidCodec;
1112     int fCurrentBRDImage;
1113     int fCurrentColorType;
1114     int fCurrentAlphaType;
1115     int fCurrentSubsetType;
1116     int fCurrentSampleSize;
1117     int fCurrentAnimSKP;
1118 };
1119 
1120 // Some runs (mostly, Valgrind) are so slow that the bot framework thinks we've hung.
1121 // This prints something every once in a while so that it knows we're still working.
start_keepalive()1122 static void start_keepalive() {
1123     static std::thread* intentionallyLeaked = new std::thread([]{
1124         for (;;) {
1125             static const int kSec = 1200;
1126         #if defined(SK_BUILD_FOR_WIN)
1127             Sleep(kSec * 1000);
1128         #else
1129             sleep(kSec);
1130         #endif
1131             SkDebugf("\nBenchmarks still running...\n");
1132         }
1133     });
1134     (void)intentionallyLeaked;
1135 }
1136 
main(int argc,char ** argv)1137 int main(int argc, char** argv) {
1138     CommandLineFlags::Parse(argc, argv);
1139 
1140     initializeEventTracingForTools();
1141 
1142 #if defined(SK_BUILD_FOR_IOS)
1143     cd_Documents();
1144 #endif
1145     SetupCrashHandler();
1146     SkAutoGraphics ag;
1147     SkTaskGroup::Enabler enabled(FLAGS_threads);
1148 
1149     SetCtxOptionsFromCommonFlags(&grContextOpts);
1150 
1151     if (kAutoTuneLoops != FLAGS_loops) {
1152         FLAGS_samples     = 1;
1153         FLAGS_gpuFrameLag = 0;
1154     }
1155 
1156     if (!FLAGS_writePath.isEmpty()) {
1157         SkDebugf("Writing files to %s.\n", FLAGS_writePath[0]);
1158         if (!sk_mkdir(FLAGS_writePath[0])) {
1159             SkDebugf("Could not create %s. Files won't be written.\n", FLAGS_writePath[0]);
1160             FLAGS_writePath.set(0, nullptr);
1161         }
1162     }
1163 
1164     std::unique_ptr<SkWStream> logStream(new SkNullWStream);
1165     if (!FLAGS_outResultsFile.isEmpty()) {
1166 #if defined(SK_RELEASE)
1167         logStream.reset(new SkFILEWStream(FLAGS_outResultsFile[0]));
1168 #else
1169         SkDebugf("I'm ignoring --outResultsFile because this is a Debug build.");
1170         return 1;
1171 #endif
1172     }
1173     NanoJSONResultsWriter log(logStream.get(), SkJSONWriter::Mode::kPretty);
1174     log.beginObject(); // root
1175 
1176     if (1 == FLAGS_properties.count() % 2) {
1177         SkDebugf("ERROR: --properties must be passed with an even number of arguments.\n");
1178         return 1;
1179     }
1180     for (int i = 1; i < FLAGS_properties.count(); i += 2) {
1181         log.appendString(FLAGS_properties[i-1], FLAGS_properties[i]);
1182     }
1183 
1184     if (1 == FLAGS_key.count() % 2) {
1185         SkDebugf("ERROR: --key must be passed with an even number of arguments.\n");
1186         return 1;
1187     }
1188     if (FLAGS_key.count()) {
1189         log.beginObject("key");
1190         for (int i = 1; i < FLAGS_key.count(); i += 2) {
1191             log.appendString(FLAGS_key[i - 1], FLAGS_key[i]);
1192         }
1193         log.endObject(); // key
1194     }
1195 
1196     const double overhead = estimate_timer_overhead();
1197     SkDebugf("Timer overhead: %s\n", HUMANIZE(overhead));
1198 
1199     SkTArray<double> samples;
1200 
1201     if (kAutoTuneLoops != FLAGS_loops) {
1202         SkDebugf("Fixed number of loops; times would only be misleading so we won't print them.\n");
1203     } else if (FLAGS_quiet) {
1204         SkDebugf("! -> high variance, ? -> moderate variance\n");
1205         SkDebugf("    micros   \tbench\n");
1206     } else if (FLAGS_ms) {
1207         SkDebugf("curr/maxrss\tloops\tmin\tmedian\tmean\tmax\tstddev\tsamples\tconfig\tbench\n");
1208     } else {
1209         SkDebugf("curr/maxrss\tloops\tmin\tmedian\tmean\tmax\tstddev\t%-*s\tconfig\tbench\n",
1210                  FLAGS_samples, "samples");
1211     }
1212 
1213     SkTArray<Config> configs;
1214     create_configs(&configs);
1215 
1216     if (FLAGS_keepAlive) {
1217         start_keepalive();
1218     }
1219 
1220     SetAnalyticAAFromCommonFlags();
1221 
1222     if (FLAGS_forceRasterPipeline) {
1223         gSkForceRasterPipelineBlitter = true;
1224     }
1225 
1226     int runs = 0;
1227     BenchmarkStream benchStream;
1228     log.beginObject("results");
1229     AutoreleasePool pool;
1230     while (Benchmark* b = benchStream.next()) {
1231         std::unique_ptr<Benchmark> bench(b);
1232         if (CommandLineFlags::ShouldSkip(FLAGS_match, bench->getUniqueName())) {
1233             continue;
1234         }
1235 
1236         if (!configs.empty()) {
1237             log.beginBench(bench->getUniqueName(), bench->getSize().fX, bench->getSize().fY);
1238             bench->delayedSetup();
1239         }
1240         for (int i = 0; i < configs.count(); ++i) {
1241             Target* target = is_enabled(b, configs[i]);
1242             if (!target) {
1243                 continue;
1244             }
1245 
1246             // During HWUI output this canvas may be nullptr.
1247             SkCanvas* canvas = target->getCanvas();
1248             const char* config = target->config.name.c_str();
1249 
1250             if (FLAGS_pre_log || FLAGS_dryRun) {
1251                 SkDebugf("Running %s\t%s\n"
1252                          , bench->getUniqueName()
1253                          , config);
1254                 if (FLAGS_dryRun) {
1255                     continue;
1256                 }
1257             }
1258 
1259             if (FLAGS_purgeBetweenBenches) {
1260                 SkGraphics::PurgeAllCaches();
1261             }
1262 
1263             TRACE_EVENT2("skia", "Benchmark", "name", TRACE_STR_COPY(bench->getUniqueName()),
1264                                               "config", TRACE_STR_COPY(config));
1265 
1266             target->setup();
1267             bench->perCanvasPreDraw(canvas);
1268 
1269             int maxFrameLag;
1270             int loops = target->needsFrameTiming(&maxFrameLag)
1271                 ? setup_gpu_bench(target, bench.get(), maxFrameLag)
1272                 : setup_cpu_bench(overhead, target, bench.get());
1273 
1274             if (kFailedLoops == loops) {
1275                 // Can't be timed.  A warning note has already been printed.
1276                 cleanup_run(target);
1277                 continue;
1278             }
1279 
1280             if (runs == 0 && FLAGS_ms < 1000) {
1281                 // Run the first bench for 1000ms to warm up the nanobench if FLAGS_ms < 1000.
1282                 // Otherwise, the first few benches' measurements will be inaccurate.
1283                 auto stop = now_ms() + 1000;
1284                 do {
1285                     time(loops, bench.get(), target);
1286                 } while (now_ms() < stop);
1287             }
1288 
1289             if (FLAGS_ms) {
1290                 samples.reset();
1291                 auto stop = now_ms() + FLAGS_ms;
1292                 do {
1293                     samples.push_back(time(loops, bench.get(), target) / loops);
1294                 } while (now_ms() < stop);
1295             } else {
1296                 samples.reset(FLAGS_samples);
1297                 for (int s = 0; s < FLAGS_samples; s++) {
1298                     samples[s] = time(loops, bench.get(), target) / loops;
1299                 }
1300             }
1301 
1302             // Scale each result to the benchmark's own units, time/unit.
1303             for (double& sample : samples) {
1304                 sample *= (1.0 / bench->getUnits());
1305             }
1306 
1307             SkTArray<SkString> keys;
1308             SkTArray<double> values;
1309             bool gpuStatsDump = FLAGS_gpuStatsDump && Benchmark::kGPU_Backend == configs[i].backend;
1310             if (gpuStatsDump) {
1311                 // TODO cache stats
1312                 bench->getGpuStats(canvas, &keys, &values);
1313             }
1314 
1315             bench->perCanvasPostDraw(canvas);
1316 
1317             if (Benchmark::kNonRendering_Backend != target->config.backend &&
1318                 !FLAGS_writePath.isEmpty() && FLAGS_writePath[0]) {
1319                 SkString pngFilename = SkOSPath::Join(FLAGS_writePath[0], config);
1320                 pngFilename = SkOSPath::Join(pngFilename.c_str(), bench->getUniqueName());
1321                 pngFilename.append(".png");
1322                 write_canvas_png(target, pngFilename);
1323             }
1324 
1325             // Building stats.plot often shows up in profiles,
1326             // so skip building it when we're not going to print it anyway.
1327             const bool want_plot = !FLAGS_quiet;
1328 
1329             Stats stats(samples, want_plot);
1330             log.beginObject(config);
1331 
1332             log.beginObject("options");
1333             log.appendString("name", bench->getName());
1334             benchStream.fillCurrentOptions(log);
1335             target->fillOptions(log);
1336             log.endObject(); // options
1337 
1338             // Metrics
1339             log.appendMetric("min_ms", stats.min);
1340             log.beginArray("samples");
1341             for (double sample : samples) {
1342                 log.appendDoubleDigits(sample, 16);
1343             }
1344             log.endArray(); // samples
1345             benchStream.fillCurrentMetrics(log);
1346             if (gpuStatsDump) {
1347                 // dump to json, only SKPBench currently returns valid keys / values
1348                 SkASSERT(keys.count() == values.count());
1349                 for (int i = 0; i < keys.count(); i++) {
1350                     log.appendMetric(keys[i].c_str(), values[i]);
1351                 }
1352             }
1353 
1354             log.endObject(); // config
1355 
1356             if (runs++ % FLAGS_flushEvery == 0) {
1357                 log.flush();
1358             }
1359 
1360             if (kAutoTuneLoops != FLAGS_loops) {
1361                 if (configs.count() == 1) {
1362                     config = ""; // Only print the config if we run the same bench on more than one.
1363                 }
1364                 SkDebugf("%4d/%-4dMB\t%s\t%s\n"
1365                          , sk_tools::getCurrResidentSetSizeMB()
1366                          , sk_tools::getMaxResidentSetSizeMB()
1367                          , bench->getUniqueName()
1368                          , config);
1369             } else if (FLAGS_quiet) {
1370                 const char* mark = " ";
1371                 const double stddev_percent =
1372                     sk_ieee_double_divide(100 * sqrt(stats.var), stats.mean);
1373                 if (stddev_percent >  5) mark = "?";
1374                 if (stddev_percent > 10) mark = "!";
1375 
1376                 SkDebugf("%10.2f %s\t%s\t%s\n",
1377                          stats.median*1e3, mark, bench->getUniqueName(), config);
1378             } else if (FLAGS_csv) {
1379                 const double stddev_percent =
1380                     sk_ieee_double_divide(100 * sqrt(stats.var), stats.mean);
1381                 SkDebugf("%g,%g,%g,%g,%g,%s,%s\n"
1382                          , stats.min
1383                          , stats.median
1384                          , stats.mean
1385                          , stats.max
1386                          , stddev_percent
1387                          , config
1388                          , bench->getUniqueName()
1389                          );
1390             } else {
1391                 const char* format = "%4d/%-4dMB\t%d\t%s\t%s\t%s\t%s\t%.0f%%\t%s\t%s\t%s\n";
1392                 const double stddev_percent =
1393                     sk_ieee_double_divide(100 * sqrt(stats.var), stats.mean);
1394                 SkDebugf(format
1395                         , sk_tools::getCurrResidentSetSizeMB()
1396                         , sk_tools::getMaxResidentSetSizeMB()
1397                         , loops
1398                         , HUMANIZE(stats.min)
1399                         , HUMANIZE(stats.median)
1400                         , HUMANIZE(stats.mean)
1401                         , HUMANIZE(stats.max)
1402                         , stddev_percent
1403                         , FLAGS_ms ? to_string(samples.count()).c_str() : stats.plot.c_str()
1404                         , config
1405                         , bench->getUniqueName()
1406                         );
1407             }
1408 
1409             if (FLAGS_gpuStats && Benchmark::kGPU_Backend == configs[i].backend) {
1410                 target->dumpStats();
1411             }
1412 
1413             if (FLAGS_verbose) {
1414                 SkDebugf("Samples:  ");
1415                 for (int i = 0; i < samples.count(); i++) {
1416                     SkDebugf("%s  ", HUMANIZE(samples[i]));
1417                 }
1418                 SkDebugf("%s\n", bench->getUniqueName());
1419             }
1420             cleanup_run(target);
1421             pool.drain();
1422         }
1423         if (!configs.empty()) {
1424             log.endBench();
1425         }
1426     }
1427 
1428     SkGraphics::PurgeAllCaches();
1429 
1430     log.beginBench("memory_usage", 0, 0);
1431     log.beginObject("meta"); // config
1432     log.appendS32("max_rss_mb", sk_tools::getMaxResidentSetSizeMB());
1433     log.endObject(); // config
1434     log.endBench();
1435 
1436     log.endObject(); // results
1437     log.endObject(); // root
1438     log.flush();
1439 
1440     return 0;
1441 }
1442