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