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