2 * Copyright 2014 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
10 #include "nanobench.h"
12 #include "Benchmark.h"
13 #include "BitmapRegionDecoderBench.h"
14 #include "CodecBench.h"
15 #include "CodecBenchPriv.h"
16 #include "CrashHandler.h"
17 #include "DecodingBench.h"
19 #include "ProcStats.h"
20 #include "ResultsWriter.h"
21 #include "RecordingBench.h"
22 #include "SKPAnimationBench.h"
24 #include "SubsetSingleBench.h"
25 #include "SubsetTranslateBench.h"
26 #include "SubsetZoomBench.h"
29 #include "SkBitmapRegionDecoder.h"
30 #include "SkBBoxHierarchy.h"
33 #include "SkCommonFlags.h"
35 #include "SkForceLinking.h"
36 #include "SkGraphics.h"
38 #include "SkPictureRecorder.h"
39 #include "SkPictureUtils.h"
41 #include "SkSurface.h"
42 #include "SkTaskGroup.h"
46 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
47 #include "nanobenchAndroid.h"
51 #include "gl/GrGLDefines.h"
53 #include "GrContextFactory.h"
54 SkAutoTDelete<GrContextFactory> gGrFactory;
57 struct GrContextOptions;
59 __SK_FORCE_IMAGE_DECODER_LINKING;
61 static const int kAutoTuneLoops = 0;
63 static const int kDefaultLoops =
70 static SkString loops_help_txt() {
72 help.printf("Number of times to run each bench. Set this to %d to auto-"
73 "tune for each bench. Timings are only reported when auto-tuning.",
78 static SkString to_string(int n) {
84 DEFINE_int32(loops, kDefaultLoops, loops_help_txt().c_str());
86 DEFINE_int32(samples, 10, "Number of samples to measure for each bench.");
87 DEFINE_int32(ms, 0, "If >0, run each bench for this many ms instead of obeying --samples.");
88 DEFINE_int32(overheadLoops, 100000, "Loops to estimate timer overhead.");
89 DEFINE_double(overheadGoal, 0.0001,
90 "Loop until timer overhead is at most this fraction of our measurments.");
91 DEFINE_double(gpuMs, 5, "Target bench time in millseconds for GPU.");
92 DEFINE_int32(gpuFrameLag, 5, "If unknown, estimated maximum number of frames GPU allows to lag.");
93 DEFINE_bool(gpuCompressAlphaMasks, false, "Compress masks generated from falling back to "
94 "software path rendering.");
96 DEFINE_string(outResultsFile, "", "If given, write results here as JSON.");
97 DEFINE_int32(maxCalibrationAttempts, 3,
98 "Try up to this many times to guess loops for a bench, or skip the bench.");
99 DEFINE_int32(maxLoops, 1000000, "Never run a bench more times than this.");
100 DEFINE_string(clip, "0,0,1000,1000", "Clip for SKPs.");
101 DEFINE_string(scales, "1.0", "Space-separated scales for SKPs.");
102 DEFINE_string(zoom, "1.0,0", "Comma-separated zoomMax,zoomPeriodMs factors for a periodic SKP zoom "
103 "function that ping-pongs between 1.0 and zoomMax.");
104 DEFINE_bool(bbh, true, "Build a BBH for SKPs?");
105 DEFINE_bool(mpd, true, "Use MultiPictureDraw for the SKPs?");
106 DEFINE_bool(loopSKP, true, "Loop SKPs like we do for micro benches?");
107 DEFINE_int32(flushEvery, 10, "Flush --outResultsFile every Nth run.");
108 DEFINE_bool(resetGpuContext, true, "Reset the GrContext before running each test.");
109 DEFINE_bool(gpuStats, false, "Print GPU stats after each gpu benchmark?");
110 DEFINE_bool(gpuStatsDump, false, "Dump GPU states after each benchmark to json");
112 static double now_ms() { return SkTime::GetNSecs() * 1e-6; }
114 static SkString humanize(double ms) {
115 if (FLAGS_verbose) return SkStringPrintf("%llu", (uint64_t)(ms*1e6));
116 return HumanizeMs(ms);
118 #define HUMANIZE(ms) humanize(ms).c_str()
120 bool Target::init(SkImageInfo info, Benchmark* bench) {
121 if (Benchmark::kRaster_Backend == config.backend) {
122 this->surface.reset(SkSurface::NewRaster(info));
123 if (!this->surface.get()) {
129 bool Target::capturePixels(SkBitmap* bmp) {
130 SkCanvas* canvas = this->getCanvas();
134 bmp->setInfo(canvas->imageInfo());
135 if (!canvas->readPixels(bmp, 0, 0)) {
136 SkDebugf("Can't read canvas pixels.\n");
143 struct GPUTarget : public Target {
144 explicit GPUTarget(const Config& c) : Target(c), gl(nullptr) { }
147 void setup() override {
148 this->gl->makeCurrent();
149 // Make sure we're done with whatever came before.
150 SK_GL(*this->gl, Finish());
152 void endTiming() override {
154 SK_GL(*this->gl, Flush());
155 this->gl->swapBuffers();
158 void fence() override {
159 SK_GL(*this->gl, Finish());
162 bool needsFrameTiming(int* maxFrameLag) const override {
163 if (!this->gl->getMaxGpuFrameLag(maxFrameLag)) {
164 // Frame lag is unknown.
165 *maxFrameLag = FLAGS_gpuFrameLag;
169 bool init(SkImageInfo info, Benchmark* bench) override {
170 uint32_t flags = this->config.useDFText ? SkSurfaceProps::kUseDeviceIndependentFonts_Flag :
172 SkSurfaceProps props(flags, SkSurfaceProps::kLegacyFontHost_InitType);
173 this->surface.reset(SkSurface::NewRenderTarget(gGrFactory->get(this->config.ctxType),
174 SkSurface::kNo_Budgeted, info,
175 this->config.samples, &props));
176 this->gl = gGrFactory->getContextInfo(this->config.ctxType)->fGLContext;
177 if (!this->surface.get()) {
180 if (!this->gl->fenceSyncSupport()) {
181 SkDebugf("WARNING: GL context for config \"%s\" does not support fence sync. "
182 "Timings might not be accurate.\n", this->config.name);
186 void fillOptions(ResultsWriter* log) override {
187 const GrGLubyte* version;
188 SK_GL_RET(*this->gl, version, GetString(GR_GL_VERSION));
189 log->configOption("GL_VERSION", (const char*)(version));
191 SK_GL_RET(*this->gl, version, GetString(GR_GL_RENDERER));
192 log->configOption("GL_RENDERER", (const char*) version);
194 SK_GL_RET(*this->gl, version, GetString(GR_GL_VENDOR));
195 log->configOption("GL_VENDOR", (const char*) version);
197 SK_GL_RET(*this->gl, version, GetString(GR_GL_SHADING_LANGUAGE_VERSION));
198 log->configOption("GL_SHADING_LANGUAGE_VERSION", (const char*) version);
204 static double time(int loops, Benchmark* bench, Target* target) {
205 SkCanvas* canvas = target->getCanvas();
207 canvas->clear(SK_ColorWHITE);
209 bench->preDraw(canvas);
210 double start = now_ms();
211 canvas = target->beginTiming(canvas);
212 bench->draw(loops, canvas);
217 double elapsed = now_ms() - start;
218 bench->postDraw(canvas);
222 static double estimate_timer_overhead() {
224 for (int i = 0; i < FLAGS_overheadLoops; i++) {
225 double start = now_ms();
226 overhead += now_ms() - start;
228 return overhead / FLAGS_overheadLoops;
231 static int detect_forever_loops(int loops) {
232 // look for a magic run-forever value
239 static int clamp_loops(int loops) {
241 SkDebugf("ERROR: clamping loops from %d to 1. "
242 "There's probably something wrong with the bench.\n", loops);
245 if (loops > FLAGS_maxLoops) {
246 SkDebugf("WARNING: clamping loops from %d to FLAGS_maxLoops, %d.\n", loops, FLAGS_maxLoops);
247 return FLAGS_maxLoops;
252 static bool write_canvas_png(Target* target, const SkString& filename) {
254 if (filename.isEmpty()) {
257 if (target->getCanvas() &&
258 kUnknown_SkColorType == target->getCanvas()->imageInfo().colorType()) {
264 if (!target->capturePixels(&bmp)) {
268 SkString dir = SkOSPath::Dirname(filename.c_str());
269 if (!sk_mkdir(dir.c_str())) {
270 SkDebugf("Can't make dir %s.\n", dir.c_str());
273 SkFILEWStream stream(filename.c_str());
274 if (!stream.isValid()) {
275 SkDebugf("Can't write %s.\n", filename.c_str());
278 if (!SkImageEncoder::EncodeStream(&stream, bmp, SkImageEncoder::kPNG_Type, 100)) {
279 SkDebugf("Can't encode a PNG.\n");
285 static int kFailedLoops = -2;
286 static int setup_cpu_bench(const double overhead, Target* target, Benchmark* bench) {
287 // First figure out approximately how many loops of bench it takes to make overhead negligible.
288 double bench_plus_overhead = 0.0;
290 int loops = bench->calculateLoops(FLAGS_loops);
291 if (kAutoTuneLoops == loops) {
292 while (bench_plus_overhead < overhead) {
293 if (round++ == FLAGS_maxCalibrationAttempts) {
294 SkDebugf("WARNING: Can't estimate loops for %s (%s vs. %s); skipping.\n",
295 bench->getUniqueName(), HUMANIZE(bench_plus_overhead), HUMANIZE(overhead));
298 bench_plus_overhead = time(1, bench, target);
302 // Later we'll just start and stop the timer once but loop N times.
303 // We'll pick N to make timer overhead negligible:
306 // ------------------------- < FLAGS_overheadGoal
307 // overhead + N * Bench Time
309 // where bench_plus_overhead ≈ overhead + Bench Time.
311 // Doing some math, we get:
313 // (overhead / FLAGS_overheadGoal) - overhead
314 // ------------------------------------------ < N
315 // bench_plus_overhead - overhead)
317 // Luckily, this also works well in practice. :)
318 if (kAutoTuneLoops == loops) {
319 const double numer = overhead / FLAGS_overheadGoal - overhead;
320 const double denom = bench_plus_overhead - overhead;
321 loops = (int)ceil(numer / denom);
322 loops = clamp_loops(loops);
324 loops = detect_forever_loops(loops);
330 static int setup_gpu_bench(Target* target, Benchmark* bench, int maxGpuFrameLag) {
331 // First, figure out how many loops it'll take to get a frame up to FLAGS_gpuMs.
332 int loops = bench->calculateLoops(FLAGS_loops);
333 if (kAutoTuneLoops == loops) {
337 if (1<<30 == loops) {
338 // We're about to wrap. Something's wrong with the bench.
343 // If the GPU lets frames lag at all, we need to make sure we're timing
344 // _this_ round, not still timing last round.
345 for (int i = 0; i < maxGpuFrameLag; i++) {
346 elapsed = time(loops, bench, target);
348 } while (elapsed < FLAGS_gpuMs);
350 // We've overshot at least a little. Scale back linearly.
351 loops = (int)ceil(loops * FLAGS_gpuMs / elapsed);
352 loops = clamp_loops(loops);
354 // Make sure we're not still timing our calibration.
357 loops = detect_forever_loops(loops);
360 // Pretty much the same deal as the calibration: do some warmup to make
361 // sure we're timing steady-state pipelined frames.
362 for (int i = 0; i < maxGpuFrameLag - 1; i++) {
363 time(loops, bench, target);
369 static SkString to_lower(const char* str) {
371 for (size_t i = 0; i < lower.size(); i++) {
372 lower[i] = tolower(lower[i]);
377 static bool is_cpu_config_allowed(const char* name) {
378 for (int i = 0; i < FLAGS_config.count(); i++) {
379 if (to_lower(FLAGS_config[i]).equals(name)) {
387 static bool is_gpu_config_allowed(const char* name, GrContextFactory::GLContextType ctxType,
389 if (!is_cpu_config_allowed(name)) {
392 if (const GrContext* ctx = gGrFactory->get(ctxType)) {
393 return sampleCnt <= ctx->caps()->maxSampleCount();
400 #define kBogusGLContextType GrContextFactory::kNative_GLContextType
402 #define kBogusGLContextType 0
405 // Append all configs that are enabled and supported.
406 static void create_configs(SkTDArray<Config>* configs) {
407 #define CPU_CONFIG(name, backend, color, alpha) \
408 if (is_cpu_config_allowed(#name)) { \
409 Config config = { #name, Benchmark::backend, color, alpha, 0, \
410 kBogusGLContextType, false }; \
411 configs->push(config); \
415 CPU_CONFIG(nonrendering, kNonRendering_Backend, kUnknown_SkColorType, kUnpremul_SkAlphaType)
416 CPU_CONFIG(8888, kRaster_Backend, kN32_SkColorType, kPremul_SkAlphaType)
417 CPU_CONFIG(565, kRaster_Backend, kRGB_565_SkColorType, kOpaque_SkAlphaType)
421 #define GPU_CONFIG(name, ctxType, samples, useDFText) \
422 if (is_gpu_config_allowed(#name, GrContextFactory::ctxType, samples)) { \
425 Benchmark::kGPU_Backend, \
427 kPremul_SkAlphaType, \
429 GrContextFactory::ctxType, \
431 configs->push(config); \
435 GPU_CONFIG(gpu, kNative_GLContextType, 0, false)
436 GPU_CONFIG(msaa4, kNative_GLContextType, 4, false)
437 GPU_CONFIG(msaa16, kNative_GLContextType, 16, false)
438 GPU_CONFIG(nvprmsaa4, kNVPR_GLContextType, 4, false)
439 GPU_CONFIG(nvprmsaa16, kNVPR_GLContextType, 16, false)
440 GPU_CONFIG(gpudft, kNative_GLContextType, 0, true)
441 GPU_CONFIG(debug, kDebug_GLContextType, 0, false)
442 GPU_CONFIG(nullgpu, kNull_GLContextType, 0, false)
444 GPU_CONFIG(angle, kANGLE_GLContextType, 0, false)
445 GPU_CONFIG(angle-gl, kANGLE_GL_GLContextType, 0, false)
447 #ifdef SK_COMMAND_BUFFER
448 GPU_CONFIG(commandbuffer, kCommandBuffer_GLContextType, 0, false)
451 GPU_CONFIG(mesa, kMESA_GLContextType, 0, false)
456 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
457 if (is_cpu_config_allowed("hwui")) {
458 Config config = { "hwui", Benchmark::kHWUI_Backend, kRGBA_8888_SkColorType,
459 kPremul_SkAlphaType, 0, kBogusGLContextType, false };
460 configs->push(config);
465 // If bench is enabled for config, returns a Target* for it, otherwise nullptr.
466 static Target* is_enabled(Benchmark* bench, const Config& config) {
467 if (!bench->isSuitableFor(config.backend)) {
471 SkImageInfo info = SkImageInfo::Make(bench->getSize().fX, bench->getSize().fY,
472 config.color, config.alpha);
474 Target* target = nullptr;
476 switch (config.backend) {
478 case Benchmark::kGPU_Backend:
479 target = new GPUTarget(config);
482 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
483 case Benchmark::kHWUI_Backend:
484 target = new HWUITarget(config, bench);
488 target = new Target(config);
492 if (!target->init(info, bench)) {
500 * We only run our subset benches on files that are supported by BitmapRegionDecoder:
501 * i.e. PNG, JPEG, and WEBP. We do *not* test WEBP, since we do not have a scanline
502 * decoder for WEBP, which is necessary for running the subset bench. (Another bench
503 * must be used to test WEBP, which decodes subsets natively.)
505 static bool run_subset_bench(const SkString& path) {
506 static const char* const exts[] = {
507 "jpg", "jpeg", "png",
508 "JPG", "JPEG", "PNG",
511 for (uint32_t i = 0; i < SK_ARRAY_COUNT(exts); i++) {
512 if (path.endsWith(exts[i])) {
521 * Returns true if set up for a subset decode succeeds, false otherwise
522 * If the set-up succeeds, the width and height parameters will be set
524 static bool valid_subset_bench(const SkString& path, SkColorType colorType,
525 int* width, int* height) {
526 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(path.c_str()));
527 SkAutoTDelete<SkMemoryStream> stream(new SkMemoryStream(encoded));
529 // Check that we can create a codec.
530 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromStream(stream.detach()));
531 if (nullptr == codec) {
532 SkDebugf("Could not create codec for %s. Skipping bench.\n", path.c_str());
536 // These will be initialized by SkCodec if the color type is kIndex8 and
538 SkPMColor colors[256];
540 const SkImageInfo info = codec->getInfo().makeColorType(colorType);
541 if (codec->startScanlineDecode(info, nullptr, colors, &colorCount) != SkCodec::kSuccess)
543 SkDebugf("Could not create scanline decoder for %s with color type %s. "
544 "Skipping bench.\n", path.c_str(), color_type_to_str(colorType));
547 *width = info.width();
548 *height = info.height();
550 // Check if the image is large enough for a meaningful subset benchmark.
551 if (*width <= 512 && *height <= 512) {
552 // This should not print a message since it is not an error.
559 static bool valid_brd_bench(SkData* encoded, SkBitmapRegionDecoder::Strategy strategy,
560 SkColorType colorType, uint32_t sampleSize, uint32_t minOutputSize, int* width,
562 SkAutoTDelete<SkBitmapRegionDecoder> brd(
563 SkBitmapRegionDecoder::Create(encoded, strategy));
564 if (nullptr == brd.get()) {
565 // This is indicates that subset decoding is not supported for a particular image format.
570 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(0, 0, brd->width(), brd->height()),
571 1, colorType, false)) {
575 if (sampleSize * minOutputSize > (uint32_t) brd->width() || sampleSize * minOutputSize >
576 (uint32_t) brd->height()) {
577 // This indicates that the image is not large enough to decode a
578 // minOutputSize x minOutputSize subset at the given sampleSize.
582 // Set the image width and height. The calling code will use this to choose subsets to decode.
583 *width = brd->width();
584 *height = brd->height();
588 static void cleanup_run(Target* target) {
591 if (FLAGS_abandonGpuContext) {
592 gGrFactory->abandonContexts();
594 if (FLAGS_resetGpuContext || FLAGS_abandonGpuContext) {
595 gGrFactory->destroyContexts();
600 class BenchmarkStream {
602 BenchmarkStream() : fBenches(BenchRegistry::Head())
603 , fGMs(skiagm::GMRegistry::Head())
604 , fCurrentRecording(0)
610 , fCurrentSubsetImage(0)
611 , fCurrentBRDImage(0)
612 , fCurrentColorType(0)
613 , fCurrentSubsetType(0)
614 , fCurrentBRDStrategy(0)
615 , fCurrentBRDSampleSize(0)
616 , fCurrentAnimSKP(0) {
617 for (int i = 0; i < FLAGS_skps.count(); i++) {
618 if (SkStrEndsWith(FLAGS_skps[i], ".skp")) {
619 fSKPs.push_back() = FLAGS_skps[i];
621 SkOSFile::Iter it(FLAGS_skps[i], ".skp");
623 while (it.next(&path)) {
624 fSKPs.push_back() = SkOSPath::Join(FLAGS_skps[0], path.c_str());
629 if (4 != sscanf(FLAGS_clip[0], "%d,%d,%d,%d",
630 &fClip.fLeft, &fClip.fTop, &fClip.fRight, &fClip.fBottom)) {
631 SkDebugf("Can't parse %s from --clip as an SkIRect.\n", FLAGS_clip[0]);
635 for (int i = 0; i < FLAGS_scales.count(); i++) {
636 if (1 != sscanf(FLAGS_scales[i], "%f", &fScales.push_back())) {
637 SkDebugf("Can't parse %s from --scales as an SkScalar.\n", FLAGS_scales[i]);
642 if (2 != sscanf(FLAGS_zoom[0], "%f,%lf", &fZoomMax, &fZoomPeriodMs)) {
643 SkDebugf("Can't parse %s from --zoom as a zoomMax,zoomPeriodMs.\n", FLAGS_zoom[0]);
648 fUseMPDs.push_back() = true;
650 fUseMPDs.push_back() = false;
652 // Prepare the images for decoding
653 for (int i = 0; i < FLAGS_images.count(); i++) {
654 const char* flag = FLAGS_images[i];
655 if (sk_isdir(flag)) {
656 // If the value passed in is a directory, add all the images
657 SkOSFile::Iter it(flag);
659 while (it.next(&file)) {
660 fImages.push_back() = SkOSPath::Join(flag, file.c_str());
662 } else if (sk_exists(flag)) {
663 // Also add the value if it is a single image
664 fImages.push_back() = flag;
668 // Choose the candidate color types for image decoding
669 const SkColorType colorTypes[] =
671 kRGB_565_SkColorType,
672 kAlpha_8_SkColorType,
673 kIndex_8_SkColorType,
674 kGray_8_SkColorType };
675 fColorTypes.reset(colorTypes, SK_ARRAY_COUNT(colorTypes));
678 static bool ReadPicture(const char* path, SkAutoTUnref<SkPicture>* pic) {
679 // Not strictly necessary, as it will be checked again later,
680 // but helps to avoid a lot of pointless work if we're going to skip it.
681 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, path)) {
685 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(path));
686 if (stream.get() == nullptr) {
687 SkDebugf("Could not read %s.\n", path);
691 pic->reset(SkPicture::CreateFromStream(stream.get()));
692 if (pic->get() == nullptr) {
693 SkDebugf("Could not read %s as an SkPicture.\n", path);
701 Benchmark* bench = fBenches->factory()(nullptr);
702 fBenches = fBenches->next();
703 fSourceType = "bench";
704 fBenchType = "micro";
709 SkAutoTDelete<skiagm::GM> gm(fGMs->factory()(nullptr));
711 if (gm->runAsBench()) {
713 fBenchType = "micro";
714 return new GMBench(gm.detach());
718 // First add all .skps as RecordingBenches.
719 while (fCurrentRecording < fSKPs.count()) {
720 const SkString& path = fSKPs[fCurrentRecording++];
721 SkAutoTUnref<SkPicture> pic;
722 if (!ReadPicture(path.c_str(), &pic)) {
725 SkString name = SkOSPath::Basename(path.c_str());
727 fBenchType = "recording";
728 fSKPBytes = static_cast<double>(SkPictureUtils::ApproximateBytesUsed(pic));
729 fSKPOps = pic->approximateOpCount();
730 return new RecordingBench(name.c_str(), pic.get(), FLAGS_bbh);
733 // Then once each for each scale as SKPBenches (playback).
734 while (fCurrentScale < fScales.count()) {
735 while (fCurrentSKP < fSKPs.count()) {
736 const SkString& path = fSKPs[fCurrentSKP];
737 SkAutoTUnref<SkPicture> pic;
738 if (!ReadPicture(path.c_str(), &pic)) {
743 while (fCurrentUseMPD < fUseMPDs.count()) {
745 // The SKP we read off disk doesn't have a BBH. Re-record so it grows one.
746 SkRTreeFactory factory;
747 SkPictureRecorder recorder;
748 static const int kFlags = SkPictureRecorder::kComputeSaveLayerInfo_RecordFlag;
749 pic->playback(recorder.beginRecording(pic->cullRect().width(),
750 pic->cullRect().height(),
752 fUseMPDs[fCurrentUseMPD] ? kFlags : 0));
753 pic.reset(recorder.endRecording());
755 SkString name = SkOSPath::Basename(path.c_str());
757 fBenchType = "playback";
758 return new SKPBench(name.c_str(), pic.get(), fClip, fScales[fCurrentScale],
759 fUseMPDs[fCurrentUseMPD++], FLAGS_loopSKP);
768 // Now loop over each skp again if we have an animation
769 if (fZoomMax != 1.0f && fZoomPeriodMs > 0) {
770 while (fCurrentAnimSKP < fSKPs.count()) {
771 const SkString& path = fSKPs[fCurrentAnimSKP];
772 SkAutoTUnref<SkPicture> pic;
773 if (!ReadPicture(path.c_str(), &pic)) {
779 SkString name = SkOSPath::Basename(path.c_str());
780 SkAutoTUnref<SKPAnimationBench::Animation> animation(
781 SKPAnimationBench::CreateZoomAnimation(fZoomMax, fZoomPeriodMs));
782 return new SKPAnimationBench(name.c_str(), pic.get(), fClip, animation,
787 for (; fCurrentCodec < fImages.count(); fCurrentCodec++) {
788 fSourceType = "image";
789 fBenchType = "skcodec";
790 const SkString& path = fImages[fCurrentCodec];
791 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(path.c_str()));
792 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
795 SkDebugf("Cannot find codec for %s\n", path.c_str());
799 while (fCurrentColorType < fColorTypes.count()) {
800 const SkColorType colorType = fColorTypes[fCurrentColorType];
803 // Make sure we can decode to this color type.
804 SkImageInfo info = codec->getInfo().makeColorType(colorType);
805 SkAlphaType alphaType;
806 if (!SkColorTypeValidateAlphaType(colorType, info.alphaType(),
810 if (alphaType != info.alphaType()) {
811 info = info.makeAlphaType(alphaType);
814 const size_t rowBytes = info.minRowBytes();
815 SkAutoMalloc storage(info.getSafeSize(rowBytes));
817 // Used if fCurrentColorType is kIndex_8_SkColorType
818 int colorCount = 256;
819 SkPMColor colors[256];
821 const SkCodec::Result result = codec->getPixels(
822 info, storage.get(), rowBytes, nullptr, colors,
825 case SkCodec::kSuccess:
826 case SkCodec::kIncompleteInput:
827 return new CodecBench(SkOSPath::Basename(path.c_str()),
829 case SkCodec::kInvalidConversion:
830 // This is okay. Not all conversions are valid.
833 // This represents some sort of failure.
838 fCurrentColorType = 0;
841 // Run the DecodingBenches
842 while (fCurrentImage < fImages.count()) {
843 fSourceType = "image";
844 fBenchType = "skimagedecoder";
845 while (fCurrentColorType < fColorTypes.count()) {
846 const SkString& path = fImages[fCurrentImage];
847 SkColorType colorType = fColorTypes[fCurrentColorType];
849 // Check if the image decodes to the right color type
850 // before creating the benchmark
852 if (SkImageDecoder::DecodeFile(path.c_str(), &bitmap,
853 colorType, SkImageDecoder::kDecodePixels_Mode)
854 && bitmap.colorType() == colorType) {
855 return new DecodingBench(path, colorType);
858 fCurrentColorType = 0;
862 // Run the SubsetBenches
863 while (fCurrentSubsetImage < fImages.count()) {
864 fSourceType = "image";
865 fBenchType = "skcodec";
866 const SkString& path = fImages[fCurrentSubsetImage];
867 if (!run_subset_bench(path)) {
868 fCurrentSubsetImage++;
871 while (fCurrentColorType < fColorTypes.count()) {
872 SkColorType colorType = fColorTypes[fCurrentColorType];
873 while (fCurrentSubsetType <= kLast_SubsetType) {
876 int currentSubsetType = fCurrentSubsetType++;
877 if (valid_subset_bench(path, colorType, &width, &height)) {
878 switch (currentSubsetType) {
879 case kTopLeft_SubsetType:
880 return new SubsetSingleBench(path, colorType, width/3,
882 case kTopRight_SubsetType:
883 return new SubsetSingleBench(path, colorType, width/3,
884 height/3, 2*width/3, 0);
885 case kMiddle_SubsetType:
886 return new SubsetSingleBench(path, colorType, width/3,
887 height/3, width/3, height/3);
888 case kBottomLeft_SubsetType:
889 return new SubsetSingleBench(path, colorType, width/3,
890 height/3, 0, 2*height/3);
891 case kBottomRight_SubsetType:
892 return new SubsetSingleBench(path, colorType, width/3,
893 height/3, 2*width/3, 2*height/3);
894 case kTranslate_SubsetType:
895 return new SubsetTranslateBench(path, colorType, 512, 512);
896 case kZoom_SubsetType:
897 return new SubsetZoomBench(path, colorType, 512, 512);
903 fCurrentSubsetType = 0;
906 fCurrentColorType = 0;
907 fCurrentSubsetImage++;
910 // Run the BRDBenches
911 // We will benchmark multiple BRD strategies.
912 static const struct {
913 SkBitmapRegionDecoder::Strategy fStrategy;
916 { SkBitmapRegionDecoder::kCanvas_Strategy, "BRD_canvas" },
917 { SkBitmapRegionDecoder::kAndroidCodec_Strategy, "BRD_android_codec" },
920 // We intend to create benchmarks that model the use cases in
921 // android/libraries/social/tiledimage. In this library, an image is decoded in 512x512
922 // tiles. The image can be translated freely, so the location of a tile may be anywhere in
923 // the image. For that reason, we will benchmark decodes in five representative locations
924 // in the image. Additionally, this use case utilizes power of two scaling, so we will
925 // test on power of two sample sizes. The output tile is always 512x512, so, when a
926 // sampleSize is used, the size of the subset that is decoded is always
927 // (sampleSize*512)x(sampleSize*512).
928 // There are a few good reasons to only test on power of two sample sizes at this time:
929 // JPEG decodes using kOriginal_Strategy are broken for non-powers of two.
930 // https://bug.skia.org/4319
931 // All use cases we are aware of only scale by powers of two.
932 // PNG decodes use the indicated sampling strategy regardless of the sample size, so
933 // these tests are sufficient to provide good coverage of our scaling options.
934 const uint32_t sampleSizes[] = { 1, 2, 4, 8, 16, 32, 64 };
935 const uint32_t minOutputSize = 512;
936 while (fCurrentBRDImage < fImages.count()) {
937 while (fCurrentBRDStrategy < (int) SK_ARRAY_COUNT(strategies)) {
938 fSourceType = "image";
939 fBenchType = strategies[fCurrentBRDStrategy].fName;
941 const SkString& path = fImages[fCurrentBRDImage];
942 const SkBitmapRegionDecoder::Strategy strategy =
943 strategies[fCurrentBRDStrategy].fStrategy;
945 while (fCurrentColorType < fColorTypes.count()) {
946 while (fCurrentBRDSampleSize < (int) SK_ARRAY_COUNT(sampleSizes)) {
947 while (fCurrentSubsetType <= kLastSingle_SubsetType) {
950 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(path.c_str()));
951 const SkColorType colorType = fColorTypes[fCurrentColorType];
952 uint32_t sampleSize = sampleSizes[fCurrentBRDSampleSize];
953 int currentSubsetType = fCurrentSubsetType++;
957 if (!valid_brd_bench(encoded.get(), strategy, colorType, sampleSize,
958 minOutputSize, &width, &height)) {
962 SkString basename = SkOSPath::Basename(path.c_str());
964 const uint32_t subsetSize = sampleSize * minOutputSize;
965 switch (currentSubsetType) {
966 case kTopLeft_SubsetType:
967 basename.append("_TopLeft");
968 subset = SkIRect::MakeXYWH(0, 0, subsetSize, subsetSize);
970 case kTopRight_SubsetType:
971 basename.append("_TopRight");
972 subset = SkIRect::MakeXYWH(width - subsetSize, 0, subsetSize,
975 case kMiddle_SubsetType:
976 basename.append("_Middle");
977 subset = SkIRect::MakeXYWH((width - subsetSize) / 2,
978 (height - subsetSize) / 2, subsetSize, subsetSize);
980 case kBottomLeft_SubsetType:
981 basename.append("_BottomLeft");
982 subset = SkIRect::MakeXYWH(0, height - subsetSize, subsetSize,
985 case kBottomRight_SubsetType:
986 basename.append("_BottomRight");
987 subset = SkIRect::MakeXYWH(width - subsetSize,
988 height - subsetSize, subsetSize, subsetSize);
994 return new BitmapRegionDecoderBench(basename.c_str(), encoded.get(),
995 strategy, colorType, sampleSize, subset);
997 fCurrentSubsetType = 0;
998 fCurrentBRDSampleSize++;
1000 fCurrentBRDSampleSize = 0;
1001 fCurrentColorType++;
1003 fCurrentColorType = 0;
1004 fCurrentBRDStrategy++;
1006 fCurrentBRDStrategy = 0;
1013 void fillCurrentOptions(ResultsWriter* log) const {
1014 log->configOption("source_type", fSourceType);
1015 log->configOption("bench_type", fBenchType);
1016 if (0 == strcmp(fSourceType, "skp")) {
1017 log->configOption("clip",
1018 SkStringPrintf("%d %d %d %d", fClip.fLeft, fClip.fTop,
1019 fClip.fRight, fClip.fBottom).c_str());
1020 SK_ALWAYSBREAK(fCurrentScale < fScales.count()); // debugging paranoia
1021 log->configOption("scale", SkStringPrintf("%.2g", fScales[fCurrentScale]).c_str());
1022 if (fCurrentUseMPD > 0) {
1023 SkASSERT(1 == fCurrentUseMPD || 2 == fCurrentUseMPD);
1024 log->configOption("multi_picture_draw", fUseMPDs[fCurrentUseMPD-1] ? "true" : "false");
1027 if (0 == strcmp(fBenchType, "recording")) {
1028 log->metric("bytes", fSKPBytes);
1029 log->metric("ops", fSKPOps);
1035 kTopLeft_SubsetType = 0,
1036 kTopRight_SubsetType = 1,
1037 kMiddle_SubsetType = 2,
1038 kBottomLeft_SubsetType = 3,
1039 kBottomRight_SubsetType = 4,
1040 kTranslate_SubsetType = 5,
1041 kZoom_SubsetType = 6,
1042 kLast_SubsetType = kZoom_SubsetType,
1043 kLastSingle_SubsetType = kBottomRight_SubsetType,
1046 const BenchRegistry* fBenches;
1047 const skiagm::GMRegistry* fGMs;
1049 SkTArray<SkScalar> fScales;
1050 SkTArray<SkString> fSKPs;
1051 SkTArray<bool> fUseMPDs;
1052 SkTArray<SkString> fImages;
1053 SkTArray<SkColorType, true> fColorTypes;
1055 double fZoomPeriodMs;
1057 double fSKPBytes, fSKPOps;
1059 const char* fSourceType; // What we're benching: bench, GM, SKP, ...
1060 const char* fBenchType; // How we bench it: micro, recording, playback, ...
1061 int fCurrentRecording;
1067 int fCurrentSubsetImage;
1068 int fCurrentBRDImage;
1069 int fCurrentColorType;
1070 int fCurrentSubsetType;
1071 int fCurrentBRDStrategy;
1072 int fCurrentBRDSampleSize;
1073 int fCurrentAnimSKP;
1076 int nanobench_main();
1077 int nanobench_main() {
1078 SetupCrashHandler();
1080 SkTaskGroup::Enabler enabled(FLAGS_threads);
1083 GrContextOptions grContextOpts;
1084 grContextOpts.fDrawPathToCompressedTexture = FLAGS_gpuCompressAlphaMasks;
1085 gGrFactory.reset(new GrContextFactory(grContextOpts));
1088 if (FLAGS_veryVerbose) {
1089 FLAGS_verbose = true;
1092 if (kAutoTuneLoops != FLAGS_loops) {
1094 FLAGS_gpuFrameLag = 0;
1097 if (!FLAGS_writePath.isEmpty()) {
1098 SkDebugf("Writing files to %s.\n", FLAGS_writePath[0]);
1099 if (!sk_mkdir(FLAGS_writePath[0])) {
1100 SkDebugf("Could not create %s. Files won't be written.\n", FLAGS_writePath[0]);
1101 FLAGS_writePath.set(0, nullptr);
1105 SkAutoTDelete<ResultsWriter> log(new ResultsWriter);
1106 if (!FLAGS_outResultsFile.isEmpty()) {
1107 log.reset(new NanoJSONResultsWriter(FLAGS_outResultsFile[0]));
1110 if (1 == FLAGS_properties.count() % 2) {
1111 SkDebugf("ERROR: --properties must be passed with an even number of arguments.\n");
1114 for (int i = 1; i < FLAGS_properties.count(); i += 2) {
1115 log->property(FLAGS_properties[i-1], FLAGS_properties[i]);
1118 if (1 == FLAGS_key.count() % 2) {
1119 SkDebugf("ERROR: --key must be passed with an even number of arguments.\n");
1122 for (int i = 1; i < FLAGS_key.count(); i += 2) {
1123 log->key(FLAGS_key[i-1], FLAGS_key[i]);
1126 const double overhead = estimate_timer_overhead();
1127 SkDebugf("Timer overhead: %s\n", HUMANIZE(overhead));
1129 SkTArray<double> samples;
1131 if (kAutoTuneLoops != FLAGS_loops) {
1132 SkDebugf("Fixed number of loops; times would only be misleading so we won't print them.\n");
1133 } else if (FLAGS_quiet) {
1134 SkDebugf("median\tbench\tconfig\n");
1135 } else if (FLAGS_ms) {
1136 SkDebugf("curr/maxrss\tloops\tmin\tmedian\tmean\tmax\tstddev\tsamples\tconfig\tbench\n");
1138 SkDebugf("curr/maxrss\tloops\tmin\tmedian\tmean\tmax\tstddev\t%-*s\tconfig\tbench\n",
1139 FLAGS_samples, "samples");
1142 SkTDArray<Config> configs;
1143 create_configs(&configs);
1146 BenchmarkStream benchStream;
1147 while (Benchmark* b = benchStream.next()) {
1148 SkAutoTDelete<Benchmark> bench(b);
1149 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, bench->getUniqueName())) {
1153 if (!configs.isEmpty()) {
1154 log->bench(bench->getUniqueName(), bench->getSize().fX, bench->getSize().fY);
1155 bench->delayedSetup();
1157 for (int i = 0; i < configs.count(); ++i) {
1158 Target* target = is_enabled(b, configs[i]);
1163 // During HWUI output this canvas may be nullptr.
1164 SkCanvas* canvas = target->getCanvas();
1165 const char* config = target->config.name;
1168 bench->perCanvasPreDraw(canvas);
1171 int loops = target->needsFrameTiming(&maxFrameLag)
1172 ? setup_gpu_bench(target, bench.get(), maxFrameLag)
1173 : setup_cpu_bench(overhead, target, bench.get());
1177 auto stop = now_ms() + FLAGS_ms;
1179 samples.push_back(time(loops, bench, target) / loops);
1180 } while (now_ms() < stop);
1182 samples.reset(FLAGS_samples);
1183 for (int s = 0; s < FLAGS_samples; s++) {
1184 samples[s] = time(loops, bench, target) / loops;
1189 SkTArray<SkString> keys;
1190 SkTArray<double> values;
1191 bool gpuStatsDump = FLAGS_gpuStatsDump && Benchmark::kGPU_Backend == configs[i].backend;
1194 bench->getGpuStats(canvas, &keys, &values);
1198 bench->perCanvasPostDraw(canvas);
1200 if (Benchmark::kNonRendering_Backend != target->config.backend &&
1201 !FLAGS_writePath.isEmpty() && FLAGS_writePath[0]) {
1202 SkString pngFilename = SkOSPath::Join(FLAGS_writePath[0], config);
1203 pngFilename = SkOSPath::Join(pngFilename.c_str(), bench->getUniqueName());
1204 pngFilename.append(".png");
1205 write_canvas_png(target, pngFilename);
1208 if (kFailedLoops == loops) {
1209 // Can't be timed. A warning note has already been printed.
1210 cleanup_run(target);
1214 Stats stats(samples);
1215 log->config(config);
1216 log->configOption("name", bench->getName());
1217 benchStream.fillCurrentOptions(log.get());
1218 target->fillOptions(log.get());
1219 log->metric("min_ms", stats.min);
1222 // dump to json, only SKPBench currently returns valid keys / values
1223 SkASSERT(keys.count() == values.count());
1224 for (int i = 0; i < keys.count(); i++) {
1225 log->metric(keys[i].c_str(), values[i]);
1230 if (runs++ % FLAGS_flushEvery == 0) {
1234 if (kAutoTuneLoops != FLAGS_loops) {
1235 if (configs.count() == 1) {
1236 config = ""; // Only print the config if we run the same bench on more than one.
1238 SkDebugf("%4d/%-4dMB\t%s\t%s\n"
1239 , sk_tools::getCurrResidentSetSizeMB()
1240 , sk_tools::getMaxResidentSetSizeMB()
1241 , bench->getUniqueName()
1243 } else if (FLAGS_quiet) {
1244 if (configs.count() == 1) {
1245 config = ""; // Only print the config if we run the same bench on more than one.
1247 SkDebugf("%s\t%s\t%s\n", HUMANIZE(stats.median), bench->getUniqueName(), config);
1249 const double stddev_percent = 100 * sqrt(stats.var) / stats.mean;
1250 SkDebugf("%4d/%-4dMB\t%d\t%s\t%s\t%s\t%s\t%.0f%%\t%s\t%s\t%s\n"
1251 , sk_tools::getCurrResidentSetSizeMB()
1252 , sk_tools::getMaxResidentSetSizeMB()
1254 , HUMANIZE(stats.min)
1255 , HUMANIZE(stats.median)
1256 , HUMANIZE(stats.mean)
1257 , HUMANIZE(stats.max)
1259 , FLAGS_ms ? to_string(samples.count()).c_str() : stats.plot.c_str()
1261 , bench->getUniqueName()
1266 if (FLAGS_gpuStats && Benchmark::kGPU_Backend == configs[i].backend) {
1267 gGrFactory->get(configs[i].ctxType)->printCacheStats();
1268 gGrFactory->get(configs[i].ctxType)->printGpuStats();
1272 if (FLAGS_verbose) {
1273 SkDebugf("Samples: ");
1274 for (int i = 0; i < samples.count(); i++) {
1275 SkDebugf("%s ", HUMANIZE(samples[i]));
1277 SkDebugf("%s\n", bench->getUniqueName());
1279 cleanup_run(target);
1283 log->bench("memory_usage", 0,0);
1284 log->config("meta");
1285 log->metric("max_rss_mb", sk_tools::getMaxResidentSetSizeMB());
1288 // Make sure we clean up the global GrContextFactory here, otherwise we might race with the
1289 // SkEventTracer destructor
1290 gGrFactory.reset(nullptr);
1296 #if !defined SK_BUILD_FOR_IOS
1297 int main(int argc, char** argv) {
1298 SkCommandLineFlags::Parse(argc, argv);
1299 return nanobench_main();