Debian Codegraph @

bench/nanobench.cpp

raw
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/CodecBench.h"
15 #include "bench/CodecBenchPriv.h"
16 #include "bench/GMBench.h"
17 #include "bench/MSKPBench.h"
18 #include "bench/RecordingBench.h"
19 #include "bench/ResultsWriter.h"
20 #include "bench/SKPAnimationBench.h"
21 #include "bench/SKPBench.h"
22 #include "bench/SkGlyphCacheBench.h"
23 #include "bench/SkSLBench.h"
24 #include "include/codec/SkAndroidCodec.h"
25 #include "include/codec/SkCodec.h"
26 #include "include/codec/SkJpegDecoder.h"
27 #include "include/core/SkBBHFactory.h"
28 #include "include/core/SkCanvas.h"
29 #include "include/core/SkData.h"
30 #include "include/core/SkGraphics.h"
31 #include "include/core/SkPictureRecorder.h"
32 #include "include/core/SkSerialProcs.h"
33 #include "include/core/SkString.h"
34 #include "include/core/SkSurface.h"
35 #include "include/encode/SkPngEncoder.h"
36 #include "include/private/base/SkMacros.h"
37 #include "src/base/SkAutoMalloc.h"
38 #include "src/base/SkLeanWindows.h"
39 #include "src/base/SkTime.h"
40 #include "src/core/SkColorSpacePriv.h"
41 #include "src/core/SkOSFile.h"
42 #include "src/core/SkTaskGroup.h"
43 #include "src/core/SkTraceEvent.h"
44 #include "src/utils/SkJSONWriter.h"
45 #include "src/utils/SkOSPath.h"
46 #include "src/utils/SkShaderUtils.h"
47 #include "tools/AutoreleasePool.h"
48 #include "tools/CrashHandler.h"
49 #include "tools/DeserialProcsUtils.h"
50 #include "tools/MSKPPlayer.h"
51 #include "tools/ProcStats.h"
52 #include "tools/Stats.h"
53 #include "tools/ToolUtils.h"
54 #include "tools/flags/CommonFlags.h"
55 #include "tools/flags/CommonFlagsConfig.h"
56 #include "tools/flags/CommonFlagsGanesh.h"
57 #include "tools/fonts/FontToolUtils.h"
58 #include "tools/ios_utils.h"
59 #include "tools/trace/EventTracingPriv.h"
60 #include "tools/trace/SkDebugfTracer.h"
61
62 #if defined(SK_ENABLE_SVG)
63 #include "modules/skshaper/utils/FactoryHelpers.h"
64 #include "modules/svg/include/SkSVGDOM.h"
65 #include "modules/svg/include/SkSVGNode.h"
66 #endif
67
68 #ifdef SK_ENABLE_ANDROID_UTILS
69 #include "bench/BitmapRegionDecoderBench.h"
70 #include "client_utils/android/BitmapRegionDecoder.h"
71 #endif
72
73 #if defined(SK_GRAPHITE)
74 #include "include/gpu/graphite/Context.h"
75 #include "include/gpu/graphite/Recorder.h"
76 #include "include/gpu/graphite/Recording.h"
77 #include "include/gpu/graphite/Surface.h"
78 #include "tools/flags/CommonFlagsGraphite.h"
79 #include "tools/graphite/ContextFactory.h"
80 #include "tools/graphite/GraphiteTestContext.h"
81 #include "tools/graphite/GraphiteToolUtils.h"
82 #endif
83
84 #if defined(SK_CODEC_DECODES_PNG_WITH_RUST)
85 #include "include/codec/SkPngRustDecoder.h"
86 #else
87 #include "include/codec/SkPngDecoder.h"
88 #endif
89
90 #include <cinttypes>
91 #include <memory>
92 #include <optional>
93 #include <stdlib.h>
94 #include <thread>
95
96 extern bool gSkForceRasterPipelineBlitter;
97 extern bool gForceHighPrecisionRasterPipeline;
98
99 #ifndef SK_BUILD_FOR_WIN
100 #include <unistd.h>
101 #endif
102
103 #include "include/gpu/ganesh/GrDirectContext.h"
104 #include "include/gpu/ganesh/SkSurfaceGanesh.h"
105 #include "src/gpu/ganesh/GrCaps.h"
106 #include "src/gpu/ganesh/GrDirectContextPriv.h"
107 #include "src/gpu/ganesh/SkGr.h"
108 #include "tools/ganesh/GrContextFactory.h"
109
110 using namespace skia_private;
111
112 using sk_gpu_test::ContextInfo;
113 using sk_gpu_test::GrContextFactory;
114 using sk_gpu_test::TestContext;
115
116 GrContextOptions grContextOpts;
117
118 #if defined(SK_GRAPHITE)
119 skiatest::graphite::TestOptions gTestOptions;
120 #endif
121
122 static const int kAutoTuneLoops = 0;
123
124 static SkString loops_help_txt() {
125 SkString help;
126 help.printf("Number of times to run each bench. Set this to %d to auto-"
127 "tune for each bench. Timings are only reported when auto-tuning.",
128 kAutoTuneLoops);
129 return help;
130 }
131
132 static SkString to_string(int n) {
133 SkString str;
134 str.appendS32(n);
135 return str;
136 }
137
138 static DEFINE_int(loops, kAutoTuneLoops, loops_help_txt().c_str());
139
140 static DEFINE_int(samples, 10, "Number of samples to measure for each bench.");
141 static DEFINE_int(ms, 0, "If >0, run each bench for this many ms instead of obeying --samples.");
142 static DEFINE_int(overheadLoops, 100000, "Loops to estimate timer overhead.");
143 static DEFINE_double(overheadGoal, 0.0001,
144 "Loop until timer overhead is at most this fraction of our measurments.");
145 static DEFINE_double(gpuMs, 5, "Target bench time in millseconds for GPU.");
146 static DEFINE_int(gpuFrameLag, 5,
147 "If unknown, estimated maximum number of frames GPU allows to lag.");
148
149 static DEFINE_string(outResultsFile, "", "If given, write results here as JSON.");
150 static DEFINE_int(maxCalibrationAttempts, 3,
151 "Try up to this many times to guess loops for a bench, or skip the bench.");
152 static DEFINE_int(maxLoops, 1000000, "Never run a bench more times than this.");
153 static DEFINE_string(clip, "0,0,1000,1000", "Clip for SKPs.");
154 static DEFINE_string(scales, "1.0", "Space-separated scales for SKPs.");
155 static DEFINE_string(zoom, "1.0,0",
156 "Comma-separated zoomMax,zoomPeriodMs factors for a periodic SKP zoom "
157 "function that ping-pongs between 1.0 and zoomMax.");
158 static DEFINE_bool(bbh, true, "Build a BBH for SKPs?");
159 static DEFINE_bool(loopSKP, true, "Loop SKPs like we do for micro benches?");
160 static DEFINE_int(flushEvery, 10, "Flush --outResultsFile every Nth run.");
161 static DEFINE_bool(gpuStats, false, "Print GPU stats after each gpu benchmark?");
162 static DEFINE_bool(gpuStatsDump, false, "Dump GPU stats after each benchmark to json");
163 static DEFINE_bool(dmsaaStatsDump, false, "Dump DMSAA stats after each benchmark to json");
164 static DEFINE_bool(keepAlive, false, "Print a message every so often so that we don't time out");
165 static DEFINE_bool(csv, false, "Print status in CSV format");
166 static DEFINE_string(sourceType, "",
167 "Apply usual --match rules to source type: bench, gm, skp, image, etc.");
168 static DEFINE_string(benchType, "",
169 "Apply usual --match rules to bench type: micro, recording, "
170 "piping, playback, skcodec, etc.");
171
172 static DEFINE_bool(forceRasterPipeline, false, "sets gSkForceRasterPipelineBlitter");
173 static DEFINE_bool(forceRasterPipelineHP, false, "sets gSkForceRasterPipelineBlitter and gForceHighPrecisionRasterPipeline");
174
175 static DEFINE_bool2(pre_log, p, false,
176 "Log before running each test. May be incomprehensible when threading");
177
178 static DEFINE_bool(cpu, true, "Run CPU-bound work?");
179 static DEFINE_bool(gpu, true, "Run GPU-bound work?");
180 static DEFINE_bool(dryRun, false,
181 "just print the tests that would be run, without actually running them.");
182 static DEFINE_string(images, "",
183 "List of images and/or directories to decode. A directory with no images"
184 " is treated as a fatal error.");
185 static DEFINE_bool(simpleCodec, false,
186 "Runs of a subset of the codec tests, always N32, Premul or Opaque");
187
188 static DEFINE_string2(match, m, nullptr,
189 "[~][^]substring[$] [...] of name to run.\n"
190 "Multiple matches may be separated by spaces.\n"
191 "~ causes a matching name to always be skipped\n"
192 "^ requires the start of the name to match\n"
193 "$ requires the end of the name to match\n"
194 "^ and $ requires an exact match\n"
195 "If a name does not match any list entry,\n"
196 "it is skipped unless some list entry starts with ~");
197
198 static DEFINE_bool2(quiet, q, false, "if true, don't print status updates.");
199 static DEFINE_bool2(verbose, v, false, "enable verbose output from the test driver.");
200
201
202 static DEFINE_string(skps, "skps", "Directory to read skps from.");
203 static DEFINE_string(mskps, "mskps", "Directory to read mskps from.");
204 static DEFINE_string(svgs, "", "Directory to read SVGs from, or a single SVG file.");
205 static DEFINE_string(texttraces, "", "Directory to read TextBlobTrace files from.");
206
207 static DEFINE_int_2(threads, j, -1,
208 "Run threadsafe tests on a threadpool with this many extra threads, "
209 "defaulting to one extra thread per core.");
210
211 static DEFINE_string2(writePath, w, "", "If set, write bitmaps here as .pngs.");
212
213 static DEFINE_string(key, "",
214 "Space-separated key/value pairs to add to JSON identifying this builder.");
215 static DEFINE_string(properties, "",
216 "Space-separated key/value pairs to add to JSON identifying this run.");
217
218 static DEFINE_bool(purgeBetweenBenches, false,
219 "Call SkGraphics::PurgeAllCaches() between each benchmark?");
220
221 static DEFINE_bool(splitPerfettoTracesByBenchmark, true,
222 "Create separate perfetto trace files for each benchmark?\n"
223 "Will only take effect if perfetto tracing is enabled. See --trace.");
224
225 static DEFINE_bool(runtimeCPUDetection, true, "Skip runtime CPU detection and optimization");
226
227 static double now_ms() { return SkTime::GetNSecs() * 1e-6; }
228
229 static SkString humanize(double ms) {
230 if (FLAGS_verbose) return SkStringPrintf("%" PRIu64, (uint64_t)(ms*1e6));
231 return HumanizeMs(ms);
232 }
233 #define HUMANIZE(ms) humanize(ms).c_str()
234
235 bool Target::init(SkImageInfo info, Benchmark* bench) {
236 if (Benchmark::Backend::kRaster == config.backend) {
237 this->surface = SkSurfaces::Raster(info);
238 if (!this->surface) {
239 return false;
240 }
241 }
242 return true;
243 }
244 bool Target::capturePixels(SkBitmap* bmp) {
245 SkCanvas* canvas = this->getCanvas();
246 if (!canvas) {
247 return false;
248 }
249 bmp->allocPixels(canvas->imageInfo());
250 if (!canvas->readPixels(*bmp, 0, 0)) {
251 SkDebugf("Can't read canvas pixels.\n");
252 return false;
253 }
254 return true;
255 }
256
257 struct GPUTarget : public Target {
258 explicit GPUTarget(const Config& c) : Target(c) {}
259 ContextInfo contextInfo;
260 std::unique_ptr<GrContextFactory> factory;
261
262 ~GPUTarget() override {
263 // For Vulkan we need to release all our refs to the GrContext before destroy the vulkan
264 // context which happens at the end of this destructor. Thus we need to release the surface
265 // here which holds a ref to the GrContext.
266 surface.reset();
267 }
268
269 void onSetup() override {
270 this->contextInfo.testContext()->makeCurrent();
271 }
272 void submitFrame() override {
273 if (this->contextInfo.testContext()) {
274 this->contextInfo.testContext()->flushAndWaitOnSync(contextInfo.directContext());
275 }
276 }
277 void submitWorkAndSyncCPU() override {
278 if (this->contextInfo.testContext()) {
279 this->contextInfo.testContext()->flushAndSyncCpu(contextInfo.directContext());
280 }
281 }
282
283 bool needsFrameTiming(int* maxFrameLag) const override {
284 if (!this->contextInfo.testContext()->getMaxGpuFrameLag(maxFrameLag)) {
285 // Frame lag is unknown.
286 *maxFrameLag = FLAGS_gpuFrameLag;
287 }
288 return true;
289 }
290 bool init(SkImageInfo info, Benchmark* bench) override {
291 GrContextOptions options = grContextOpts;
292 bench->modifyGrContextOptions(&options);
293 this->factory = std::make_unique<GrContextFactory>(options);
294 SkSurfaceProps props(this->config.surfaceFlags, kRGB_H_SkPixelGeometry);
295 this->surface = SkSurfaces::RenderTarget(
296 this->factory->get(this->config.ctxType, this->config.ctxOverrides),
297 skgpu::Budgeted::kNo,
298 info,
299 this->config.samples,
300 &props);
301 this->contextInfo =
302 this->factory->getContextInfo(this->config.ctxType, this->config.ctxOverrides);
303 if (!this->surface) {
304 return false;
305 }
306 if (!this->contextInfo.testContext()->fenceSyncSupport()) {
307 SkDebugf("WARNING: GL context for config \"%s\" does not support fence sync. "
308 "Timings might not be accurate.\n", this->config.name.c_str());
309 }
310 return true;
311 }
312
313 void dumpStats() override {
314 auto context = this->contextInfo.directContext();
315
316 context->priv().printCacheStats();
317 context->priv().printGpuStats();
318 context->priv().printContextStats();
319 }
320 };
321
322 #if defined(SK_GRAPHITE)
323 struct GraphiteTarget : public Target {
324 explicit GraphiteTarget(const Config& c) : Target(c) {}
325 using TestContext = skiatest::graphite::GraphiteTestContext;
326 using ContextFactory = skiatest::graphite::ContextFactory;
327
328 std::unique_ptr<ContextFactory> factory;
329
330 TestContext* testContext;
331 skgpu::graphite::Context* context;
332 std::unique_ptr<skgpu::graphite::Recorder> recorder;
333
334 ~GraphiteTarget() override {
335 // For Vulkan we need to release all our refs before we destroy the vulkan context which
336 // happens at the end of this destructor. Thus we need to release the surface here which
337 // holds a ref to the Graphite device
338 surface.reset();
339 }
340 void submitFrame() override {
341 if (context && recorder) {
342 std::unique_ptr<skgpu::graphite::Recording> recording = this->recorder->snap();
343 if (recording) {
344 this->testContext->submitRecordingAndWaitOnSync(this->context, recording.get());
345 }
346 }
347 }
348 void submitWorkAndSyncCPU() override {
349 if (context && recorder) {
350 // TODO: have a way to sync work with out submitting a Recording which is currently
351 // required. Probably need to get to the point where the backend command buffers are
352 // stored on the Context and not Recordings before this is feasible.
353 std::unique_ptr<skgpu::graphite::Recording> recording = this->recorder->snap();
354 if (recording) {
355 skgpu::graphite::InsertRecordingInfo info;
356 info.fRecording = recording.get();
357 this->context->insertRecording(info);
358 }
359 this->context->submit(skgpu::graphite::SyncToCpu::kYes);
360 }
361 }
362
363 bool needsFrameTiming(int* maxFrameLag) const override {
364 SkAssertResult(this->testContext->getMaxGpuFrameLag(maxFrameLag));
365 return true;
366 }
367 bool init(SkImageInfo info, Benchmark* bench) override {
368 skiatest::graphite::TestOptions testOptions = gTestOptions;
369 testOptions.fContextOptions.fRequireOrderedRecordings = true;
370 bench->modifyGraphiteContextOptions(&testOptions.fContextOptions);
371
372 this->factory = std::make_unique<ContextFactory>(testOptions);
373
374 skiatest::graphite::ContextInfo ctxInfo =
375 this->factory->getContextInfo(this->config.ctxType);
376 if (!ctxInfo.fContext) {
377 return false;
378 }
379 this->testContext = ctxInfo.fTestContext;
380 this->context = ctxInfo.fContext;
381
382 this->recorder = this->context->makeRecorder(ToolUtils::CreateTestingRecorderOptions());
383 if (!this->recorder) {
384 return false;
385 }
386
387 this->surface = SkSurfaces::RenderTarget(this->recorder.get(), info);
388 if (!this->surface) {
389 return false;
390 }
391 // TODO: get fence stuff working
392 #if 0
393 if (!this->contextInfo.testContext()->fenceSyncSupport()) {
394 SkDebugf("WARNING: GL context for config \"%s\" does not support fence sync. "
395 "Timings might not be accurate.\n", this->config.name.c_str());
396 }
397 #endif
398 return true;
399 }
400
401 void dumpStats() override {
402 }
403 };
404 #endif // SK_GRAPHITE
405
406 static double time(int loops, Benchmark* bench, Target* target) {
407 SkCanvas* canvas = target->getCanvas();
408 if (canvas) {
409 canvas->clear(SK_ColorWHITE);
410 }
411 bench->preDraw(canvas);
412 double start = now_ms();
413 canvas = target->beginTiming(canvas);
414
415 auto submitFrame = [target]() { target->submitFrame(); };
416
417 bench->draw(loops, canvas, submitFrame);
418
419 double elapsed = now_ms() - start;
420 bench->postDraw(canvas);
421 return elapsed;
422 }
423
424 static double estimate_timer_overhead() {
425 double overhead = 0;
426 for (int i = 0; i < FLAGS_overheadLoops; i++) {
427 double start = now_ms();
428 overhead += now_ms() - start;
429 }
430 return overhead / FLAGS_overheadLoops;
431 }
432
433 static int detect_forever_loops(int loops) {
434 // look for a magic run-forever value
435 if (loops < 0) {
436 loops = SK_MaxS32;
437 }
438 return loops;
439 }
440
441 static int clamp_loops(int loops) {
442 if (loops < 1) {
443 SkDebugf("ERROR: clamping loops from %d to 1. "
444 "There's probably something wrong with the bench.\n", loops);
445 return 1;
446 }
447 if (loops > FLAGS_maxLoops) {
448 SkDebugf("WARNING: clamping loops from %d to FLAGS_maxLoops, %d.\n", loops, FLAGS_maxLoops);
449 return FLAGS_maxLoops;
450 }
451 return loops;
452 }
453
454 static bool write_canvas_png(Target* target, const SkString& filename) {
455
456 if (filename.isEmpty()) {
457 return false;
458 }
459 if (target->getCanvas() &&
460 kUnknown_SkColorType == target->getCanvas()->imageInfo().colorType()) {
461 return false;
462 }
463
464 SkBitmap bmp;
465
466 if (!target->capturePixels(&bmp)) {
467 return false;
468 }
469
470 SkString dir = SkOSPath::Dirname(filename.c_str());
471 if (!sk_mkdir(dir.c_str())) {
472 SkDebugf("Can't make dir %s.\n", dir.c_str());
473 return false;
474 }
475 SkFILEWStream stream(filename.c_str());
476 if (!stream.isValid()) {
477 SkDebugf("Can't write %s.\n", filename.c_str());
478 return false;
479 }
480 if (!SkPngEncoder::Encode(&stream, bmp.pixmap(), {})) {
481 SkDebugf("Can't encode a PNG.\n");
482 return false;
483 }
484 return true;
485 }
486
487 static int kFailedLoops = -2;
488 static int setup_cpu_bench(const double overhead, Target* target, Benchmark* bench) {
489 // First figure out approximately how many loops of bench it takes to make overhead negligible.
490 double bench_plus_overhead = 0.0;
491 int round = 0;
492 int loops = bench->shouldLoop() ? FLAGS_loops : 1;
493 if (kAutoTuneLoops == loops) {
494 while (bench_plus_overhead < overhead) {
495 if (round++ == FLAGS_maxCalibrationAttempts) {
496 SkDebugf("WARNING: Can't estimate loops for %s (%s vs. %s); skipping.\n",
497 bench->getUniqueName(), HUMANIZE(bench_plus_overhead), HUMANIZE(overhead));
498 return kFailedLoops;
499 }
500 bench_plus_overhead = time(1, bench, target);
501 }
502 }
503
504 // Later we'll just start and stop the timer once but loop N times.
505 // We'll pick N to make timer overhead negligible:
506 //
507 // overhead
508 // ------------------------- < FLAGS_overheadGoal
509 // overhead + N * Bench Time
510 //
511 // where bench_plus_overhead ~=~ overhead + Bench Time.
512 //
513 // Doing some math, we get:
514 //
515 // (overhead / FLAGS_overheadGoal) - overhead
516 // ------------------------------------------ < N
517 // bench_plus_overhead - overhead)
518 //
519 // Luckily, this also works well in practice. :)
520 if (kAutoTuneLoops == loops) {
521 const double numer = overhead / FLAGS_overheadGoal - overhead;
522 const double denom = bench_plus_overhead - overhead;
523 loops = (int)ceil(numer / denom);
524 loops = clamp_loops(loops);
525 } else {
526 loops = detect_forever_loops(loops);
527 }
528
529 return loops;
530 }
531
532 static int setup_gpu_bench(Target* target, Benchmark* bench, int maxGpuFrameLag) {
533 // First, figure out how many loops it'll take to get a frame up to FLAGS_gpuMs.
534 int loops = bench->shouldLoop() ? FLAGS_loops : 1;
535 if (kAutoTuneLoops == loops) {
536 loops = 1;
537 double elapsed = 0;
538 do {
539 if (1<<30 == loops) {
540 // We're about to wrap. Something's wrong with the bench.
541 loops = 0;
542 break;
543 }
544 loops *= 2;
545 // If the GPU lets frames lag at all, we need to make sure we're timing
546 // _this_ round, not still timing last round.
547 for (int i = 0; i < maxGpuFrameLag; i++) {
548 elapsed = time(loops, bench, target);
549 }
550 } while (elapsed < FLAGS_gpuMs);
551
552 // We've overshot at least a little. Scale back linearly.
553 loops = (int)ceil(loops * FLAGS_gpuMs / elapsed);
554 loops = clamp_loops(loops);
555
556 // Make sure we're not still timing our calibration.
557 target->submitWorkAndSyncCPU();
558
559 // Pretty much the same deal as the calibration: do some warmup to make
560 // sure we're timing steady-state pipelined frames.
561 for (int i = 0; i < maxGpuFrameLag; i++) {
562 time(loops, bench, target);
563 }
564 } else {
565 // We skip running the bench for calibration or to reach a steady state. When an explicit
566 // loop count is provided, we want to just run that number of loops.
567 loops = detect_forever_loops(loops);
568 }
569
570
571 return loops;
572 }
573
574 #define kBogusContextType skgpu::ContextType::kGL
575 #define kBogusContextOverrides GrContextFactory::ContextOverrides::kNone
576
577 static std::optional<Config> create_config(const SkCommandLineConfig* config) {
578 if (const auto* gpuConfig = config->asConfigGpu()) {
579 if (!FLAGS_gpu) {
580 SkDebugf("Skipping config '%s' as requested.\n", config->getTag().c_str());
581 return std::nullopt;
582 }
583
584 const auto ctxType = gpuConfig->getContextType();
585 const auto ctxOverrides = gpuConfig->getContextOverrides();
586 const auto sampleCount = gpuConfig->getSamples();
587 const auto colorType = gpuConfig->getColorType();
588 if (gpuConfig->getSurfType() != SkCommandLineConfigGpu::SurfType::kDefault) {
589 SkDebugf("This tool only supports the default surface type.");
590 return std::nullopt;
591 }
592
593 GrContextFactory factory(grContextOpts);
594 if (const auto ctx = factory.get(ctxType, ctxOverrides)) {
595 GrBackendFormat format = ctx->defaultBackendFormat(colorType, GrRenderable::kYes);
596 int supportedSampleCount =
597 ctx->priv().caps()->getRenderTargetSampleCount(sampleCount, format);
598 if (sampleCount != supportedSampleCount) {
599 SkDebugf("Configuration '%s' sample count %d is not a supported sample count.\n",
600 config->getTag().c_str(),
601 sampleCount);
602 return std::nullopt;
603 }
604 } else {
605 SkDebugf("No context was available matching config '%s'.\n", config->getTag().c_str());
606 return std::nullopt;
607 }
608
609 return Config{gpuConfig->getTag(),
610 Benchmark::Backend::kGanesh,
611 colorType,
612 kPremul_SkAlphaType,
613 config->refColorSpace(),
614 sampleCount,
615 ctxType,
616 ctxOverrides,
617 gpuConfig->getSurfaceFlags()};
618 }
619 #if defined(SK_GRAPHITE)
620 if (const auto* gpuConfig = config->asConfigGraphite()) {
621 if (!FLAGS_gpu) {
622 SkDebugf("Skipping config '%s' as requested.\n", config->getTag().c_str());
623 return std::nullopt;
624 }
625
626 const auto graphiteCtxType = gpuConfig->getContextType();
627 const auto sampleCount = 1; // TODO: gpuConfig->getSamples();
628 const auto colorType = gpuConfig->getColorType();
629
630 using ContextFactory = skiatest::graphite::ContextFactory;
631
632 ContextFactory factory(gTestOptions);
633 skiatest::graphite::ContextInfo ctxInfo = factory.getContextInfo(graphiteCtxType);
634 skgpu::graphite::Context* ctx = ctxInfo.fContext;
635 if (ctx) {
636 // TODO: Add graphite ctx queries for supported sample count by color type.
637 #if 0
638 GrBackendFormat format = ctx->defaultBackendFormat(colorType, GrRenderable::kYes);
639 int supportedSampleCount =
640 ctx->priv().caps()->getRenderTargetSampleCount(sampleCount, format);
641 if (sampleCount != supportedSampleCount) {
642 SkDebugf("Configuration '%s' sample count %d is not a supported sample count.\n",
643 config->getTag().c_str(),
644 sampleCount);
645 return std::nullopt;
646 }
647 #else
648 if (sampleCount > 1) {
649 SkDebugf("Configuration '%s' sample count %d is not a supported sample count.\n",
650 config->getTag().c_str(),
651 sampleCount);
652 return std::nullopt;
653 }
654 #endif
655 } else {
656 SkDebugf("No context was available matching config '%s'.\n", config->getTag().c_str());
657 return std::nullopt;
658 }
659
660 return Config{gpuConfig->getTag(),
661 Benchmark::Backend::kGraphite,
662 colorType,
663 kPremul_SkAlphaType,
664 config->refColorSpace(),
665 sampleCount,
666 graphiteCtxType,
667 kBogusContextOverrides,
668 0};
669 }
670 #endif
671
672 #define CPU_CONFIG(name, backend, color, alpha) \
673 if (config->getBackend().equals(name)) { \
674 if (!FLAGS_cpu) { \
675 SkDebugf("Skipping config '%s' as requested.\n", config->getTag().c_str()); \
676 return std::nullopt; \
677 } \
678 return Config{SkString(name), \
679 Benchmark::backend, \
680 color, \
681 alpha, \
682 config->refColorSpace(), \
683 0, \
684 kBogusContextType, \
685 kBogusContextOverrides, \
686 0}; \
687 }
688
689 CPU_CONFIG("nonrendering", Backend::kNonRendering, kUnknown_SkColorType, kUnpremul_SkAlphaType)
690
691 CPU_CONFIG("a8", Backend::kRaster, kAlpha_8_SkColorType, kPremul_SkAlphaType)
692 CPU_CONFIG("gray8", Backend::kRaster, kGray_8_SkColorType, kOpaque_SkAlphaType)
693 CPU_CONFIG("r8", Backend::kRaster, kR8_unorm_SkColorType, kOpaque_SkAlphaType)
694 CPU_CONFIG("565", Backend::kRaster, kRGB_565_SkColorType, kOpaque_SkAlphaType)
695 CPU_CONFIG("8888", Backend::kRaster, kN32_SkColorType, kPremul_SkAlphaType)
696 CPU_CONFIG("rgba", Backend::kRaster, kRGBA_8888_SkColorType, kPremul_SkAlphaType)
697 CPU_CONFIG("bgra", Backend::kRaster, kBGRA_8888_SkColorType, kPremul_SkAlphaType)
698 CPU_CONFIG("f16", Backend::kRaster, kRGBA_F16_SkColorType, kPremul_SkAlphaType)
699 CPU_CONFIG("srgba", Backend::kRaster, kSRGBA_8888_SkColorType, kPremul_SkAlphaType)
700
701 #undef CPU_CONFIG
702
703 SkDebugf("Unknown config '%s'.\n", config->getTag().c_str());
704 return std::nullopt;
705 }
706
707 // Append all configs that are enabled and supported.
708 void create_configs(TArray<Config>* configs) {
709 SkCommandLineConfigArray array;
710 ParseConfigs(FLAGS_config, &array);
711 for (int i = 0; i < array.size(); ++i) {
712 if (std::optional<Config> config = create_config(array[i].get())) {
713 configs->push_back(*config);
714 }
715 }
716
717 // If no just default configs were requested, then we're okay.
718 if (array.size() == 0 || FLAGS_config.size() == 0 ||
719 // Otherwise, make sure that all specified configs have been created.
720 array.size() == configs->size()) {
721 return;
722 }
723 exit(1);
724 }
725
726 // disable warning : switch statement contains default but no 'case' labels
727 #if defined _WIN32
728 #pragma warning ( push )
729 #pragma warning ( disable : 4065 )
730 #endif
731
732 // If bench is enabled for config, returns a Target* for it, otherwise nullptr.
733 static Target* is_enabled(Benchmark* bench, const Config& config) {
734 if (!bench->isSuitableFor(config.backend)) {
735 return nullptr;
736 }
737
738 SkImageInfo info =
739 SkImageInfo::Make(bench->getSize(), config.color, config.alpha, config.colorSpace);
740
741 Target* target = nullptr;
742
743 switch (config.backend) {
744 case Benchmark::Backend::kGanesh:
745 target = new GPUTarget(config);
746 break;
747 #if defined(SK_GRAPHITE)
748 case Benchmark::Backend::kGraphite:
749 target = new GraphiteTarget(config);
750 break;
751 #endif
752 default:
753 target = new Target(config);
754 break;
755 }
756
757 if (!target->init(info, bench)) {
758 delete target;
759 return nullptr;
760 }
761 return target;
762 }
763
764 #if defined _WIN32
765 #pragma warning ( pop )
766 #endif
767
768 #ifdef SK_ENABLE_ANDROID_UTILS
769 static bool valid_brd_bench(sk_sp<SkData> encoded, SkColorType colorType, uint32_t sampleSize,
770 uint32_t minOutputSize, int* width, int* height) {
771 auto brd = android::skia::BitmapRegionDecoder::Make(encoded);
772 if (nullptr == brd) {
773 // This is indicates that subset decoding is not supported for a particular image format.
774 return false;
775 }
776
777 if (sampleSize * minOutputSize > (uint32_t) brd->width() || sampleSize * minOutputSize >
778 (uint32_t) brd->height()) {
779 // This indicates that the image is not large enough to decode a
780 // minOutputSize x minOutputSize subset at the given sampleSize.
781 return false;
782 }
783
784 // Set the image width and height. The calling code will use this to choose subsets to decode.
785 *width = brd->width();
786 *height = brd->height();
787 return true;
788 }
789 #endif
790
791 static void cleanup_run(Target* target) {
792 delete target;
793 }
794
795 static void collect_files(const CommandLineFlags::StringArray& paths,
796 const char* ext,
797 TArray<SkString>* list) {
798 for (int i = 0; i < paths.size(); ++i) {
799 if (SkStrEndsWith(paths[i], ext)) {
800 list->push_back(SkString(paths[i]));
801 } else {
802 SkOSFile::Iter it(paths[i], ext);
803 SkString path;
804 while (it.next(&path)) {
805 list->push_back(SkOSPath::Join(paths[i], path.c_str()));
806 }
807 }
808 }
809 }
810
811 class BenchmarkStream {
812 public:
813 BenchmarkStream() : fBenches(BenchRegistry::Head())
814 , fGMs(skiagm::GMRegistry::Head()) {
815 collect_files(FLAGS_skps, ".skp", &fSKPs);
816 collect_files(FLAGS_mskps, ".mskp", &fMSKPs);
817 collect_files(FLAGS_svgs, ".svg", &fSVGs);
818 collect_files(FLAGS_texttraces, ".trace", &fTextBlobTraces);
819
820 if (4 != sscanf(FLAGS_clip[0], "%d,%d,%d,%d",
821 &fClip.fLeft, &fClip.fTop, &fClip.fRight, &fClip.fBottom)) {
822 SkDebugf("Can't parse %s from --clip as an SkIRect.\n", FLAGS_clip[0]);
823 exit(1);
824 }
825
826 for (int i = 0; i < FLAGS_scales.size(); i++) {
827 if (1 != sscanf(FLAGS_scales[i], "%f", &fScales.push_back())) {
828 SkDebugf("Can't parse %s from --scales as an SkScalar.\n", FLAGS_scales[i]);
829 exit(1);
830 }
831 }
832
833 if (2 != sscanf(FLAGS_zoom[0], "%f,%lf", &fZoomMax, &fZoomPeriodMs)) {
834 SkDebugf("Can't parse %s from --zoom as a zoomMax,zoomPeriodMs.\n", FLAGS_zoom[0]);
835 exit(1);
836 }
837
838 // Prepare the images for decoding
839 if (!CommonFlags::CollectImages(FLAGS_images, &fImages)) {
840 exit(1);
841 }
842
843 // Choose the candidate color types for image decoding
844 fColorTypes.push_back(kN32_SkColorType);
845 if (!FLAGS_simpleCodec) {
846 fColorTypes.push_back(kRGB_565_SkColorType);
847 fColorTypes.push_back(kAlpha_8_SkColorType);
848 fColorTypes.push_back(kGray_8_SkColorType);
849 }
850 }
851
852 static sk_sp<SkPicture> ReadPicture(const char* path) {
853 // Not strictly necessary, as it will be checked again later,
854 // but helps to avoid a lot of pointless work if we're going to skip it.
855 if (CommandLineFlags::ShouldSkip(FLAGS_match, SkOSPath::Basename(path).c_str())) {
856 return nullptr;
857 }
858
859 std::unique_ptr<SkStream> stream = SkStream::MakeFromFile(path);
860 if (!stream) {
861 SkDebugf("Could not read %s.\n", path);
862 return nullptr;
863 }
864 SkDeserialProcs procs = ToolUtils::get_default_skp_deserial_procs();
865 return SkPicture::MakeFromStream(stream.get(), &procs);
866 }
867
868 static std::unique_ptr<MSKPPlayer> ReadMSKP(const char* path) {
869 // Not strictly necessary, as it will be checked again later,
870 // but helps to avoid a lot of pointless work if we're going to skip it.
871 if (CommandLineFlags::ShouldSkip(FLAGS_match, SkOSPath::Basename(path).c_str())) {
872 return nullptr;
873 }
874
875 std::unique_ptr<SkStreamSeekable> stream = SkStream::MakeFromFile(path);
876 if (!stream) {
877 SkDebugf("Could not read %s.\n", path);
878 return nullptr;
879 }
880
881 return MSKPPlayer::Make(stream.get());
882 }
883
884 static sk_sp<SkPicture> ReadSVGPicture(const char* path) {
885 if (CommandLineFlags::ShouldSkip(FLAGS_match, SkOSPath::Basename(path).c_str())) {
886 return nullptr;
887 }
888 sk_sp<SkData> data(SkData::MakeFromFileName(path));
889 if (!data) {
890 SkDebugf("Could not read %s.\n", path);
891 return nullptr;
892 }
893
894 #if defined(SK_ENABLE_SVG)
895 SkMemoryStream stream(std::move(data));
896 sk_sp<SkSVGDOM> svgDom = SkSVGDOM::Builder()
897 .setFontManager(ToolUtils::TestFontMgr())
898 .setTextShapingFactory(SkShapers::BestAvailable())
899 .make(stream);
900 if (!svgDom) {
901 SkDebugf("Could not parse %s.\n", path);
902 return nullptr;
903 }
904
905 // Use the intrinsic SVG size if available, otherwise fall back to a default value.
906 static const SkSize kDefaultContainerSize = SkSize::Make(128, 128);
907 if (svgDom->containerSize().isEmpty()) {
908 svgDom->setContainerSize(kDefaultContainerSize);
909 }
910
911 SkPictureRecorder recorder;
912 svgDom->render(recorder.beginRecording(svgDom->containerSize().width(),
913 svgDom->containerSize().height()));
914 return recorder.finishRecordingAsPicture();
915 #else
916 return nullptr;
917 #endif // defined(SK_ENABLE_SVG)
918 }
919
920 Benchmark* next() {
921 std::unique_ptr<Benchmark> bench;
922 do {
923 bench.reset(this->rawNext());
924 if (!bench) {
925 return nullptr;
926 }
927 } while (CommandLineFlags::ShouldSkip(FLAGS_sourceType, fSourceType) ||
928 CommandLineFlags::ShouldSkip(FLAGS_benchType, fBenchType));
929 return bench.release();
930 }
931
932 Benchmark* rawNext() {
933 if (fBenches) {
934 Benchmark* bench = fBenches->get()(nullptr);
935 fBenches = fBenches->next();
936 fSourceType = "bench";
937 fBenchType = "micro";
938 return bench;
939 }
940
941 while (fGMs) {
942 std::unique_ptr<skiagm::GM> gm = fGMs->get()();
943 fGMs = fGMs->next();
944 if (gm->runAsBench()) {
945 fSourceType = "gm";
946 fBenchType = "micro";
947 return new GMBench(std::move(gm));
948 }
949 }
950
951 while (fCurrentTextBlobTrace < fTextBlobTraces.size()) {
952 SkString path = fTextBlobTraces[fCurrentTextBlobTrace++];
953 SkString basename = SkOSPath::Basename(path.c_str());
954 static constexpr char kEnding[] = ".trace";
955 if (basename.endsWith(kEnding)) {
956 basename.remove(basename.size() - strlen(kEnding), strlen(kEnding));
957 }
958 fSourceType = "texttrace";
959 fBenchType = "micro";
960 return CreateDiffCanvasBench(
961 SkStringPrintf("SkDiffBench-%s", basename.c_str()),
962 [path](){ return SkStream::MakeFromFile(path.c_str()); });
963 }
964
965 // First add all .skps as RecordingBenches.
966 while (fCurrentRecording < fSKPs.size()) {
967 const SkString& path = fSKPs[fCurrentRecording++];
968 sk_sp<SkPicture> pic = ReadPicture(path.c_str());
969 if (!pic) {
970 continue;
971 }
972 SkString name = SkOSPath::Basename(path.c_str());
973 fSourceType = "skp";
974 fBenchType = "recording";
975 fSKPBytes = static_cast<double>(pic->approximateBytesUsed());
976 fSKPOps = pic->approximateOpCount();
977 return new RecordingBench(name.c_str(), pic.get(), FLAGS_bbh);
978 }
979
980 // Add all .skps as DeserializePictureBenchs.
981 while (fCurrentDeserialPicture < fSKPs.size()) {
982 const SkString& path = fSKPs[fCurrentDeserialPicture++];
983 sk_sp<SkData> data = SkData::MakeFromFileName(path.c_str());
984 if (!data) {
985 continue;
986 }
987 SkString name = SkOSPath::Basename(path.c_str());
988 fSourceType = "skp";
989 fBenchType = "deserial";
990 fSKPBytes = static_cast<double>(data->size());
991 fSKPOps = 0;
992 return new DeserializePictureBench(name.c_str(), std::move(data));
993 }
994
995 // Then once each for each scale as SKPBenches (playback).
996 while (fCurrentScale < fScales.size()) {
997 while (fCurrentSKP < fSKPs.size()) {
998 const SkString& path = fSKPs[fCurrentSKP++];
999 sk_sp<SkPicture> pic = ReadPicture(path.c_str());
1000 if (!pic) {
1001 continue;
1002 }
1003
1004 if (FLAGS_bbh) {
1005 // The SKP we read off disk doesn't have a BBH. Re-record so it grows one.
1006 SkRTreeFactory factory;
1007 SkPictureRecorder recorder;
1008 pic->playback(recorder.beginRecording(pic->cullRect().width(),
1009 pic->cullRect().height(),
1010 &factory));
1011 pic = recorder.finishRecordingAsPicture();
1012 }
1013 SkString name = SkOSPath::Basename(path.c_str());
1014 fSourceType = "skp";
1015 fBenchType = "playback";
1016 return new SKPBench(name.c_str(), pic.get(), fClip, fScales[fCurrentScale],
1017 FLAGS_loopSKP);
1018 }
1019
1020 while (fCurrentSVG < fSVGs.size()) {
1021 const char* path = fSVGs[fCurrentSVG++].c_str();
1022 if (sk_sp<SkPicture> pic = ReadSVGPicture(path)) {
1023 fSourceType = "svg";
1024 fBenchType = "playback";
1025 return new SKPBench(SkOSPath::Basename(path).c_str(), pic.get(), fClip,
1026 fScales[fCurrentScale], FLAGS_loopSKP);
1027 }
1028 }
1029
1030 fCurrentSKP = 0;
1031 fCurrentSVG = 0;
1032 fCurrentScale++;
1033 }
1034
1035 // Now loop over each skp again if we have an animation
1036 if (fZoomMax != 1.0f && fZoomPeriodMs > 0) {
1037 while (fCurrentAnimSKP < fSKPs.size()) {
1038 const SkString& path = fSKPs[fCurrentAnimSKP];
1039 sk_sp<SkPicture> pic = ReadPicture(path.c_str());
1040 if (!pic) {
1041 fCurrentAnimSKP++;
1042 continue;
1043 }
1044
1045 fCurrentAnimSKP++;
1046 SkString name = SkOSPath::Basename(path.c_str());
1047 sk_sp<SKPAnimationBench::Animation> animation =
1048 SKPAnimationBench::MakeZoomAnimation(fZoomMax, fZoomPeriodMs);
1049 return new SKPAnimationBench(name.c_str(), pic.get(), fClip, std::move(animation),
1050 FLAGS_loopSKP);
1051 }
1052 }
1053
1054 // Read all MSKPs as benches
1055 while (fCurrentMSKP < fMSKPs.size()) {
1056 const SkString& path = fMSKPs[fCurrentMSKP++];
1057 std::unique_ptr<MSKPPlayer> player = ReadMSKP(path.c_str());
1058 if (!player) {
1059 continue;
1060 }
1061 SkString name = SkOSPath::Basename(path.c_str());
1062 fSourceType = "mskp";
1063 fBenchType = "mskp";
1064 return new MSKPBench(std::move(name), std::move(player));
1065 }
1066
1067 for (; fCurrentCodec < fImages.size(); fCurrentCodec++) {
1068 fSourceType = "image";
1069 fBenchType = "skcodec";
1070 const SkString& path = fImages[fCurrentCodec];
1071 if (CommandLineFlags::ShouldSkip(FLAGS_match, path.c_str())) {
1072 continue;
1073 }
1074 sk_sp<SkData> encoded(SkData::MakeFromFileName(path.c_str()));
1075 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
1076 if (!codec) {
1077 // Nothing to time.
1078 SkDebugf("Cannot find codec for %s\n", path.c_str());
1079 continue;
1080 }
1081
1082 while (fCurrentColorType < fColorTypes.size()) {
1083 const SkColorType colorType = fColorTypes[fCurrentColorType];
1084
1085 SkAlphaType alphaType = codec->getInfo().alphaType();
1086 if (FLAGS_simpleCodec) {
1087 if (kUnpremul_SkAlphaType == alphaType) {
1088 alphaType = kPremul_SkAlphaType;
1089 }
1090
1091 fCurrentColorType++;
1092 } else {
1093 switch (alphaType) {
1094 case kOpaque_SkAlphaType:
1095 // We only need to test one alpha type (opaque).
1096 fCurrentColorType++;
1097 break;
1098 case kUnpremul_SkAlphaType:
1099 case kPremul_SkAlphaType:
1100 if (0 == fCurrentAlphaType) {
1101 // Test unpremul first.
1102 alphaType = kUnpremul_SkAlphaType;
1103 fCurrentAlphaType++;
1104 } else {
1105 // Test premul.
1106 alphaType = kPremul_SkAlphaType;
1107 fCurrentAlphaType = 0;
1108 fCurrentColorType++;
1109 }
1110 break;
1111 default:
1112 SkASSERT(false);
1113 fCurrentColorType++;
1114 break;
1115 }
1116 }
1117
1118 // Make sure we can decode to this color type and alpha type.
1119 SkImageInfo info =
1120 codec->getInfo().makeColorType(colorType).makeAlphaType(alphaType);
1121 const size_t rowBytes = info.minRowBytes();
1122 SkAutoMalloc storage(info.computeByteSize(rowBytes));
1123
1124 const SkCodec::Result result = codec->getPixels(
1125 info, storage.get(), rowBytes);
1126 switch (result) {
1127 case SkCodec::kSuccess:
1128 case SkCodec::kIncompleteInput:
1129 return new CodecBench(SkOSPath::Basename(path.c_str()),
1130 encoded.get(), colorType, alphaType);
1131 case SkCodec::kInvalidConversion:
1132 // This is okay. Not all conversions are valid.
1133 break;
1134 default:
1135 // This represents some sort of failure.
1136 SkASSERT(false);
1137 break;
1138 }
1139 }
1140 fCurrentColorType = 0;
1141 }
1142
1143 // Run AndroidCodecBenches
1144 const int sampleSizes[] = { 2, 4, 8 };
1145 for (; fCurrentAndroidCodec < fImages.size(); fCurrentAndroidCodec++) {
1146 fSourceType = "image";
1147 fBenchType = "skandroidcodec";
1148
1149 const SkString& path = fImages[fCurrentAndroidCodec];
1150 if (CommandLineFlags::ShouldSkip(FLAGS_match, path.c_str())) {
1151 continue;
1152 }
1153 sk_sp<SkData> encoded(SkData::MakeFromFileName(path.c_str()));
1154 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(encoded));
1155 if (!codec) {
1156 // Nothing to time.
1157 SkDebugf("Cannot find codec for %s\n", path.c_str());
1158 continue;
1159 }
1160
1161 while (fCurrentSampleSize < (int) std::size(sampleSizes)) {
1162 int sampleSize = sampleSizes[fCurrentSampleSize];
1163 fCurrentSampleSize++;
1164 if (10 * sampleSize > std::min(codec->getInfo().width(), codec->getInfo().height())) {
1165 // Avoid benchmarking scaled decodes of already small images.
1166 break;
1167 }
1168
1169 return new AndroidCodecBench(SkOSPath::Basename(path.c_str()),
1170 encoded.get(), sampleSize);
1171 }
1172 fCurrentSampleSize = 0;
1173 }
1174
1175 #ifdef SK_ENABLE_ANDROID_UTILS
1176 // Run the BRDBenches
1177 // We intend to create benchmarks that model the use cases in
1178 // android/libraries/social/tiledimage. In this library, an image is decoded in 512x512
1179 // tiles. The image can be translated freely, so the location of a tile may be anywhere in
1180 // the image. For that reason, we will benchmark decodes in five representative locations
1181 // in the image. Additionally, this use case utilizes power of two scaling, so we will
1182 // test on power of two sample sizes. The output tile is always 512x512, so, when a
1183 // sampleSize is used, the size of the subset that is decoded is always
1184 // (sampleSize*512)x(sampleSize*512).
1185 // There are a few good reasons to only test on power of two sample sizes at this time:
1186 // All use cases we are aware of only scale by powers of two.
1187 // PNG decodes use the indicated sampling strategy regardless of the sample size, so
1188 // these tests are sufficient to provide good coverage of our scaling options.
1189 const uint32_t brdSampleSizes[] = { 1, 2, 4, 8, 16 };
1190 const uint32_t minOutputSize = 512;
1191 for (; fCurrentBRDImage < fImages.size(); fCurrentBRDImage++) {
1192 fSourceType = "image";
1193 fBenchType = "BRD";
1194
1195 const SkString& path = fImages[fCurrentBRDImage];
1196 if (CommandLineFlags::ShouldSkip(FLAGS_match, path.c_str())) {
1197 continue;
1198 }
1199
1200 while (fCurrentColorType < fColorTypes.size()) {
1201 while (fCurrentSampleSize < (int) std::size(brdSampleSizes)) {
1202 while (fCurrentSubsetType <= kLastSingle_SubsetType) {
1203
1204 sk_sp<SkData> encoded(SkData::MakeFromFileName(path.c_str()));
1205 const SkColorType colorType = fColorTypes[fCurrentColorType];
1206 uint32_t sampleSize = brdSampleSizes[fCurrentSampleSize];
1207 int currentSubsetType = fCurrentSubsetType++;
1208
1209 int width = 0;
1210 int height = 0;
1211 if (!valid_brd_bench(encoded, colorType, sampleSize, minOutputSize,
1212 &width, &height)) {
1213 break;
1214 }
1215
1216 SkString basename = SkOSPath::Basename(path.c_str());
1217 SkIRect subset;
1218 const uint32_t subsetSize = sampleSize * minOutputSize;
1219 switch (currentSubsetType) {
1220 case kTopLeft_SubsetType:
1221 basename.append("_TopLeft");
1222 subset = SkIRect::MakeXYWH(0, 0, subsetSize, subsetSize);
1223 break;
1224 case kTopRight_SubsetType:
1225 basename.append("_TopRight");
1226 subset = SkIRect::MakeXYWH(width - subsetSize, 0, subsetSize,
1227 subsetSize);
1228 break;
1229 case kMiddle_SubsetType:
1230 basename.append("_Middle");
1231 subset = SkIRect::MakeXYWH((width - subsetSize) / 2,
1232 (height - subsetSize) / 2, subsetSize, subsetSize);
1233 break;
1234 case kBottomLeft_SubsetType:
1235 basename.append("_BottomLeft");
1236 subset = SkIRect::MakeXYWH(0, height - subsetSize, subsetSize,
1237 subsetSize);
1238 break;
1239 case kBottomRight_SubsetType:
1240 basename.append("_BottomRight");
1241 subset = SkIRect::MakeXYWH(width - subsetSize,
1242 height - subsetSize, subsetSize, subsetSize);
1243 break;
1244 default:
1245 SkASSERT(false);
1246 }
1247
1248 return new BitmapRegionDecoderBench(basename.c_str(), encoded.get(),
1249 colorType, sampleSize, subset);
1250 }
1251 fCurrentSubsetType = 0;
1252 fCurrentSampleSize++;
1253 }
1254 fCurrentSampleSize = 0;
1255 fCurrentColorType++;
1256 }
1257 fCurrentColorType = 0;
1258 }
1259 #endif // SK_ENABLE_ANDROID_UTILS
1260
1261 return nullptr;
1262 }
1263
1264 void fillCurrentOptions(NanoJSONResultsWriter& log) const {
1265 log.appendCString("source_type", fSourceType);
1266 log.appendCString("bench_type", fBenchType);
1267 if (0 == strcmp(fSourceType, "skp")) {
1268 log.appendString("clip",
1269 SkStringPrintf("%d %d %d %d", fClip.fLeft, fClip.fTop,
1270 fClip.fRight, fClip.fBottom));
1271 SkASSERT_RELEASE(fCurrentScale < fScales.size()); // debugging paranoia
1272 log.appendString("scale", SkStringPrintf("%.2g", fScales[fCurrentScale]));
1273 }
1274 }
1275
1276 void fillCurrentMetrics(NanoJSONResultsWriter& log) const {
1277 if (0 == strcmp(fBenchType, "recording")) {
1278 log.appendMetric("bytes", fSKPBytes);
1279 log.appendMetric("ops", fSKPOps);
1280 }
1281 }
1282
1283 private:
1284 #ifdef SK_ENABLE_ANDROID_UTILS
1285 enum SubsetType {
1286 kTopLeft_SubsetType = 0,
1287 kTopRight_SubsetType = 1,
1288 kMiddle_SubsetType = 2,
1289 kBottomLeft_SubsetType = 3,
1290 kBottomRight_SubsetType = 4,
1291 kTranslate_SubsetType = 5,
1292 kZoom_SubsetType = 6,
1293 kLast_SubsetType = kZoom_SubsetType,
1294 kLastSingle_SubsetType = kBottomRight_SubsetType,
1295 };
1296 #endif
1297
1298 const BenchRegistry* fBenches;
1299 const skiagm::GMRegistry* fGMs;
1300 SkIRect fClip;
1301 TArray<SkScalar> fScales;
1302 TArray<SkString> fSKPs;
1303 TArray<SkString> fMSKPs;
1304 TArray<SkString> fSVGs;
1305 TArray<SkString> fTextBlobTraces;
1306 TArray<SkString> fImages;
1307 TArray<SkColorType, true> fColorTypes;
1308 SkScalar fZoomMax;
1309 double fZoomPeriodMs;
1310
1311 double fSKPBytes, fSKPOps;
1312
1313 const char* fSourceType; // What we're benching: bench, GM, SKP, ...
1314 const char* fBenchType; // How we bench it: micro, recording, playback, ...
1315 int fCurrentRecording = 0;
1316 int fCurrentDeserialPicture = 0;
1317 int fCurrentMSKP = 0;
1318 int fCurrentScale = 0;
1319 int fCurrentSKP = 0;
1320 int fCurrentSVG = 0;
1321 int fCurrentTextBlobTrace = 0;
1322 int fCurrentCodec = 0;
1323 int fCurrentAndroidCodec = 0;
1324 #ifdef SK_ENABLE_ANDROID_UTILS
1325 int fCurrentBRDImage = 0;
1326 int fCurrentSubsetType = 0;
1327 #endif
1328 int fCurrentColorType = 0;
1329 int fCurrentAlphaType = 0;
1330 int fCurrentSampleSize = 0;
1331 int fCurrentAnimSKP = 0;
1332 };
1333
1334 // Some runs are so slow that the Swarming thinks we've hung.
1335 // This prints something every once in a while so that it knows we're still working.
1336 static void start_keepalive() {
1337 static std::thread* intentionallyLeaked = new std::thread([]{
1338 for (;;) {
1339 static const int kSec = 1200;
1340 #if defined(SK_BUILD_FOR_WIN)
1341 Sleep(kSec * 1000);
1342 #else
1343 sleep(kSec);
1344 #endif
1345 SkDebugf("\nBenchmarks still running...\n");
1346 }
1347 });
1348 (void)intentionallyLeaked;
1349 SK_INTENTIONALLY_LEAKED(intentionallyLeaked);
1350 }
1351
1352 class NanobenchShaderErrorHandler : public GrContextOptions::ShaderErrorHandler {
1353 void compileError(const char* shader, const char* errors) override {
1354 // Nanobench should abort if any shader can't compile. Failure is much better than
1355 // reporting meaningless performance metrics.
1356 std::string message = SkShaderUtils::BuildShaderErrorMessage(shader, errors);
1357 SK_ABORT("\n%s", message.c_str());
1358 }
1359 };
1360
1361 int main(int argc, char** argv) {
1362 CommandLineFlags::Parse(argc, argv);
1363
1364 initializeEventTracingForTools();
1365
1366 #if defined(SK_BUILD_FOR_IOS)
1367 cd_Documents();
1368 #endif
1369 SetupCrashHandler();
1370 if (FLAGS_runtimeCPUDetection) {
1371 SkGraphics::Init();
1372 }
1373
1374 // Our benchmarks only currently decode .png or .jpg files
1375 #if defined(SK_CODEC_DECODES_PNG_WITH_RUST)
1376 SkCodecs::Register(SkPngRustDecoder::Decoder());
1377 #else
1378 SkCodecs::Register(SkPngDecoder::Decoder());
1379 #endif
1380 SkCodecs::Register(SkJpegDecoder::Decoder());
1381
1382 SkTaskGroup::Enabler enabled(FLAGS_threads);
1383
1384 CommonFlags::SetCtxOptions(&grContextOpts);
1385
1386 #if defined(SK_GRAPHITE)
1387 CommonFlags::SetTestOptions(&gTestOptions);
1388 #endif
1389
1390 NanobenchShaderErrorHandler errorHandler;
1391 grContextOpts.fShaderErrorHandler = &errorHandler;
1392
1393 if (kAutoTuneLoops != FLAGS_loops) {
1394 FLAGS_samples = 1;
1395 FLAGS_gpuFrameLag = 0;
1396 }
1397
1398 if (!FLAGS_writePath.isEmpty()) {
1399 SkDebugf("Writing files to %s.\n", FLAGS_writePath[0]);
1400 if (!sk_mkdir(FLAGS_writePath[0])) {
1401 SkDebugf("Could not create %s. Files won't be written.\n", FLAGS_writePath[0]);
1402 FLAGS_writePath.set(0, nullptr);
1403 }
1404 }
1405
1406 std::unique_ptr<SkWStream> logStream(new SkNullWStream);
1407 if (!FLAGS_outResultsFile.isEmpty()) {
1408 #if defined(SK_RELEASE)
1409 logStream.reset(new SkFILEWStream(FLAGS_outResultsFile[0]));
1410 #else
1411 SkDebugf("I'm ignoring --outResultsFile because this is a Debug build.");
1412 return 1;
1413 #endif
1414 }
1415 NanoJSONResultsWriter log(logStream.get(), SkJSONWriter::Mode::kPretty);
1416 log.beginObject(); // root
1417
1418 if (1 == FLAGS_properties.size() % 2) {
1419 SkDebugf("ERROR: --properties must be passed with an even number of arguments.\n");
1420 return 1;
1421 }
1422 for (int i = 1; i < FLAGS_properties.size(); i += 2) {
1423 log.appendCString(FLAGS_properties[i-1], FLAGS_properties[i]);
1424 }
1425
1426 if (1 == FLAGS_key.size() % 2) {
1427 SkDebugf("ERROR: --key must be passed with an even number of arguments.\n");
1428 return 1;
1429 }
1430 if (FLAGS_key.size()) {
1431 log.beginObject("key");
1432 for (int i = 1; i < FLAGS_key.size(); i += 2) {
1433 log.appendCString(FLAGS_key[i - 1], FLAGS_key[i]);
1434 }
1435 log.endObject(); // key
1436 }
1437
1438 const double overhead = estimate_timer_overhead();
1439 if (!FLAGS_quiet && !FLAGS_csv) {
1440 SkDebugf("Timer overhead: %s\n", HUMANIZE(overhead));
1441 }
1442
1443 TArray<double> samples;
1444
1445 if (kAutoTuneLoops != FLAGS_loops) {
1446 SkDebugf("Fixed number of loops; times would only be misleading so we won't print them.\n");
1447 } else if (FLAGS_quiet) {
1448 SkDebugf("! -> high variance, ? -> moderate variance\n");
1449 SkDebugf(" micros \tbench\n");
1450 } else if (FLAGS_csv) {
1451 SkDebugf("min,median,mean,max,stddev,config,bench\n");
1452 } else if (FLAGS_ms) {
1453 SkDebugf("curr/maxrss\tloops\tmin\tmedian\tmean\tmax\tstddev\tsamples\tconfig\tbench\n");
1454 } else {
1455 SkDebugf("curr/maxrss\tloops\tmin\tmedian\tmean\tmax\tstddev\t%-*s\tconfig\tbench\n",
1456 FLAGS_samples, "samples");
1457 }
1458
1459 GrRecordingContextPriv::DMSAAStats combinedDMSAAStats;
1460
1461 TArray<Config> configs;
1462 create_configs(&configs);
1463
1464 if (FLAGS_keepAlive) {
1465 start_keepalive();
1466 }
1467
1468 gSkForceRasterPipelineBlitter = FLAGS_forceRasterPipelineHP || FLAGS_forceRasterPipeline;
1469 gForceHighPrecisionRasterPipeline = FLAGS_forceRasterPipelineHP;
1470
1471 // The SkSL memory benchmark must run before any GPU painting occurs. SkSL allocates memory for
1472 // its modules the first time they are accessed, and this test is trying to measure the size of
1473 // those allocations. If a paint has already occurred, some modules will have already been
1474 // loaded, so we won't be able to capture a delta for them.
1475 log.beginObject("results");
1476 RunSkSLModuleBenchmarks(&log);
1477
1478 int runs = 0;
1479 BenchmarkStream benchStream;
1480 AutoreleasePool pool;
1481 while (Benchmark* b = benchStream.next()) {
1482 std::unique_ptr<Benchmark> bench(b);
1483 if (CommandLineFlags::ShouldSkip(FLAGS_match, bench->getUniqueName())) {
1484 continue;
1485 }
1486
1487 if (!configs.empty()) {
1488 log.beginBench(
1489 bench->getUniqueName(), bench->getSize().width(), bench->getSize().height());
1490 bench->delayedSetup();
1491 }
1492 for (int i = 0; i < configs.size(); ++i) {
1493 Target* target = is_enabled(b, configs[i]);
1494 if (!target) {
1495 continue;
1496 }
1497
1498 // During HWUI output this canvas may be nullptr.
1499 SkCanvas* canvas = target->getCanvas();
1500 const char* config = target->config.name.c_str();
1501
1502 if (FLAGS_pre_log || FLAGS_dryRun) {
1503 SkDebugf("Running %s\t%s\n"
1504 , bench->getUniqueName()
1505 , config);
1506 if (FLAGS_dryRun) {
1507 continue;
1508 }
1509 }
1510
1511 if (FLAGS_purgeBetweenBenches) {
1512 SkGraphics::PurgeAllCaches();
1513 }
1514
1515 if (FLAGS_splitPerfettoTracesByBenchmark) {
1516 TRACE_EVENT_API_NEW_TRACE_SECTION(TRACE_STR_COPY(bench->getUniqueName()));
1517 }
1518 TRACE_EVENT2("skia", "Benchmark", "name", TRACE_STR_COPY(bench->getUniqueName()),
1519 "config", TRACE_STR_COPY(config));
1520
1521 target->setup();
1522 bench->perCanvasPreDraw(canvas);
1523
1524 int maxFrameLag;
1525 int loops = target->needsFrameTiming(&maxFrameLag)
1526 ? setup_gpu_bench(target, bench.get(), maxFrameLag)
1527 : setup_cpu_bench(overhead, target, bench.get());
1528
1529 if (kFailedLoops == loops) {
1530 // Can't be timed. A warning note has already been printed.
1531 cleanup_run(target);
1532 continue;
1533 }
1534
1535 if (runs == 0 && FLAGS_ms < 1000 && kAutoTuneLoops == FLAGS_loops) {
1536 // Run the first bench for 1000ms to warm up the nanobench if FLAGS_ms < 1000.
1537 // Otherwise, the first few benches' measurements will be inaccurate.
1538 auto stop = now_ms() + 1000;
1539 do {
1540 time(loops, bench.get(), target);
1541 pool.drain();
1542 } while (now_ms() < stop);
1543 }
1544
1545 if (FLAGS_ms) {
1546 samples.clear();
1547 auto stop = now_ms() + FLAGS_ms;
1548 do {
1549 samples.push_back(time(loops, bench.get(), target) / loops);
1550 pool.drain();
1551 } while (now_ms() < stop);
1552 } else {
1553 samples.reset(FLAGS_samples);
1554 for (int s = 0; s < FLAGS_samples; s++) {
1555 samples[s] = time(loops, bench.get(), target) / loops;
1556 pool.drain();
1557 }
1558 }
1559
1560 // Scale each result to the benchmark's own units, time/unit.
1561 for (double& sample : samples) {
1562 sample *= (1.0 / bench->getUnits());
1563 }
1564
1565 TArray<SkString> keys;
1566 TArray<double> values;
1567 if (configs[i].backend == Benchmark::Backend::kGanesh) {
1568 if (FLAGS_gpuStatsDump) {
1569 // TODO cache stats
1570 bench->getGpuStats(canvas, &keys, &values);
1571 }
1572 if (FLAGS_dmsaaStatsDump && bench->getDMSAAStats(canvas->recordingContext())) {
1573 const auto& dmsaaStats = canvas->recordingContext()->priv().dmsaaStats();
1574 dmsaaStats.dumpKeyValuePairs(&keys, &values);
1575 dmsaaStats.dump();
1576 combinedDMSAAStats.merge(dmsaaStats);
1577 }
1578 }
1579
1580 bench->perCanvasPostDraw(canvas);
1581
1582 if (Benchmark::Backend::kNonRendering != target->config.backend &&
1583 !FLAGS_writePath.isEmpty() && FLAGS_writePath[0]) {
1584 SkString pngFilename = SkOSPath::Join(FLAGS_writePath[0], config);
1585 pngFilename = SkOSPath::Join(pngFilename.c_str(), bench->getUniqueName());
1586 pngFilename.append(".png");
1587 write_canvas_png(target, pngFilename);
1588 }
1589
1590 // Building stats.plot often shows up in profiles,
1591 // so skip building it when we're not going to print it anyway.
1592 const bool want_plot = !FLAGS_quiet && !FLAGS_ms;
1593
1594 Stats stats(samples, want_plot);
1595 log.beginObject(config);
1596
1597 log.beginObject("options");
1598 log.appendCString("name", bench->getName());
1599 benchStream.fillCurrentOptions(log);
1600 log.endObject(); // options
1601
1602 // Metrics
1603 log.appendMetric("min_ms", stats.min);
1604 log.appendMetric("min_ratio", sk_ieee_double_divide(stats.median, stats.min));
1605 log.beginArray("samples");
1606 for (double sample : samples) {
1607 log.appendDoubleDigits(sample, 16);
1608 }
1609 log.endArray(); // samples
1610 benchStream.fillCurrentMetrics(log);
1611 if (!keys.empty()) {
1612 // dump to json, only SKPBench currently returns valid keys / values
1613 SkASSERT(keys.size() == values.size());
1614 for (int j = 0; j < keys.size(); j++) {
1615 log.appendMetric(keys[j].c_str(), values[j]);
1616 }
1617 }
1618
1619 log.endObject(); // config
1620
1621 if (runs++ % FLAGS_flushEvery == 0) {
1622 log.flush();
1623 }
1624
1625 if (kAutoTuneLoops != FLAGS_loops) {
1626 if (configs.size() == 1) {
1627 config = ""; // Only print the config if we run the same bench on more than one.
1628 }
1629 SkDebugf("%4d/%-4dMB\t%s\t%s "
1630 , sk_tools::getCurrResidentSetSizeMB()
1631 , sk_tools::getMaxResidentSetSizeMB()
1632 , bench->getUniqueName()
1633 , config);
1634 SkDebugf("\n");
1635 } else if (FLAGS_quiet) {
1636 const char* mark = " ";
1637 const double stddev_percent =
1638 sk_ieee_double_divide(100 * sqrt(stats.var), stats.mean);
1639 if (stddev_percent > 5) mark = "?";
1640 if (stddev_percent > 10) mark = "!";
1641
1642 SkDebugf("%10.2f %s\t%s\t%s\n",
1643 stats.median*1e3, mark, bench->getUniqueName(), config);
1644 } else if (FLAGS_csv) {
1645 const double stddev_percent =
1646 sk_ieee_double_divide(100 * sqrt(stats.var), stats.mean);
1647 SkDebugf("%g,%g,%g,%g,%g,%s,%s\n"
1648 , stats.min
1649 , stats.median
1650 , stats.mean
1651 , stats.max
1652 , stddev_percent
1653 , config
1654 , bench->getUniqueName()
1655 );
1656 } else {
1657 const double stddev_percent =
1658 sk_ieee_double_divide(100 * sqrt(stats.var), stats.mean);
1659 SkDebugf("%4d/%-4dMB\t%d\t%s\t%s\t%s\t%s\t%.0f%%\t%s\t%s\t%s\n"
1660 , sk_tools::getCurrResidentSetSizeMB()
1661 , sk_tools::getMaxResidentSetSizeMB()
1662 , loops
1663 , HUMANIZE(stats.min)
1664 , HUMANIZE(stats.median)
1665 , HUMANIZE(stats.mean)
1666 , HUMANIZE(stats.max)
1667 , stddev_percent
1668 , FLAGS_ms ? to_string(samples.size()).c_str() : stats.plot.c_str()
1669 , config
1670 , bench->getUniqueName()
1671 );
1672 }
1673
1674 if (FLAGS_gpuStats && Benchmark::Backend::kGanesh == configs[i].backend) {
1675 target->dumpStats();
1676 }
1677
1678 if (FLAGS_verbose) {
1679 SkDebugf("Samples: ");
1680 for (int j = 0; j < samples.size(); j++) {
1681 SkDebugf("%s ", HUMANIZE(samples[j]));
1682 }
1683 SkDebugf("%s\n", bench->getUniqueName());
1684 }
1685 cleanup_run(target);
1686 pool.drain();
1687 }
1688 if (!configs.empty()) {
1689 log.endBench();
1690 }
1691 }
1692
1693 if (FLAGS_dmsaaStatsDump) {
1694 SkDebugf("<<Total Combined DMSAA Stats>>\n");
1695 combinedDMSAAStats.dump();
1696 }
1697
1698 SkGraphics::PurgeAllCaches();
1699
1700 log.beginBench("memory_usage", 0, 0);
1701 log.beginObject("meta"); // config
1702 log.appendS32("max_rss_mb", sk_tools::getMaxResidentSetSizeMB());
1703 log.endObject(); // config
1704 log.endBench();
1705
1706 log.endObject(); // results
1707 log.endObject(); // root
1708 log.flush();
1709
1710 return 0;
1711 }