From 10d49ea696d7e9f71ef6cdc4094ef59a5b45d190 Mon Sep 17 00:00:00 2001 From: Jim Graham Date: Fri, 3 Sep 2021 16:26:01 -0700 Subject: [PATCH] Add RasterCache metrics to the FrameTimings (flutter/engine#28439) --- engine/src/flutter/common/settings.h | 19 +++ engine/src/flutter/flow/frame_timings.cc | 52 +++++++- engine/src/flutter/flow/frame_timings.h | 24 +++- .../flow/frame_timings_recorder_unittests.cc | 116 ++++++++++++++++++ engine/src/flutter/flow/raster_cache.cc | 3 +- engine/src/flutter/flow/raster_cache.h | 20 +++ .../flutter/flow/testing/mock_raster_cache.cc | 28 +++++ .../flutter/flow/testing/mock_raster_cache.h | 34 +++++ .../flutter/lib/ui/platform_dispatcher.dart | 89 ++++++++++++-- .../lib/ui/window/platform_configuration.h | 13 +- .../lib/src/ui/platform_dispatcher.dart | 54 ++++++-- .../lib/web_ui/test/frame_timings_common.dart | 4 + engine/src/flutter/shell/common/rasterizer.cc | 9 +- engine/src/flutter/shell/common/shell.cc | 11 +- .../src/flutter/testing/dart/window_test.dart | 37 +++++- 15 files changed, 478 insertions(+), 35 deletions(-) diff --git a/engine/src/flutter/common/settings.h b/engine/src/flutter/common/settings.h index c6289d92e2..e087be8d0a 100644 --- a/engine/src/flutter/common/settings.h +++ b/engine/src/flutter/common/settings.h @@ -37,6 +37,8 @@ class FrameTiming { kVsyncStart, kBuildStart, kBuildFinish, kRasterStart, kRasterFinish, kRasterFinishWallTime}; + static constexpr int kStatisticsCount = kCount + 5; + fml::TimePoint Get(Phase phase) const { return data_[phase]; } fml::TimePoint Set(Phase phase, fml::TimePoint value) { return data_[phase] = value; @@ -44,10 +46,27 @@ class FrameTiming { uint64_t GetFrameNumber() const { return frame_number_; } void SetFrameNumber(uint64_t frame_number) { frame_number_ = frame_number; } + uint64_t GetLayerCacheCount() const { return layer_cache_count_; } + uint64_t GetLayerCacheBytes() const { return layer_cache_bytes_; } + uint64_t GetPictureCacheCount() const { return picture_cache_count_; } + uint64_t GetPictureCacheBytes() const { return picture_cache_bytes_; } + void SetRasterCacheStatistics(size_t layer_cache_count, + size_t layer_cache_bytes, + size_t picture_cache_count, + size_t picture_cache_bytes) { + layer_cache_count_ = layer_cache_count; + layer_cache_bytes_ = layer_cache_bytes; + picture_cache_count_ = picture_cache_count; + picture_cache_bytes_ = picture_cache_bytes; + } private: fml::TimePoint data_[kCount]; uint64_t frame_number_; + size_t layer_cache_count_; + size_t layer_cache_bytes_; + size_t picture_cache_count_; + size_t picture_cache_bytes_; }; using TaskObserverAdd = diff --git a/engine/src/flutter/flow/frame_timings.cc b/engine/src/flutter/flow/frame_timings.cc index b5169c1621..6ead668c36 100644 --- a/engine/src/flutter/flow/frame_timings.cc +++ b/engine/src/flutter/flow/frame_timings.cc @@ -79,6 +79,34 @@ fml::TimeDelta FrameTimingsRecorder::GetBuildDuration() const { return build_end_ - build_start_; } +/// Count of the layer cache entries +size_t FrameTimingsRecorder::GetLayerCacheCount() const { + std::scoped_lock state_lock(state_mutex_); + FML_DCHECK(state_ >= State::kRasterEnd); + return layer_cache_count_; +} + +/// Total bytes in all layer cache entries +size_t FrameTimingsRecorder::GetLayerCacheBytes() const { + std::scoped_lock state_lock(state_mutex_); + FML_DCHECK(state_ >= State::kRasterEnd); + return layer_cache_bytes_; +} + +/// Count of the picture cache entries +size_t FrameTimingsRecorder::GetPictureCacheCount() const { + std::scoped_lock state_lock(state_mutex_); + FML_DCHECK(state_ >= State::kRasterEnd); + return picture_cache_count_; +} + +/// Total bytes in all picture cache entries +size_t FrameTimingsRecorder::GetPictureCacheBytes() const { + std::scoped_lock state_lock(state_mutex_); + FML_DCHECK(state_ >= State::kRasterEnd); + return picture_cache_bytes_; +} + void FrameTimingsRecorder::RecordVsync(fml::TimePoint vsync_start, fml::TimePoint vsync_target) { std::scoped_lock state_lock(state_mutex_); @@ -102,19 +130,32 @@ void FrameTimingsRecorder::RecordBuildEnd(fml::TimePoint build_end) { build_end_ = build_end; } -void FrameTimingsRecorder::RecordRasterStart(fml::TimePoint raster_start) { +void FrameTimingsRecorder::RecordRasterStart(fml::TimePoint raster_start, + const RasterCache* cache) { std::scoped_lock state_lock(state_mutex_); FML_DCHECK(state_ == State::kBuildEnd); state_ = State::kRasterStart; raster_start_ = raster_start; + sweep_count_at_raster_start_ = cache ? cache->sweep_count() : -1; } -FrameTiming FrameTimingsRecorder::RecordRasterEnd() { +FrameTiming FrameTimingsRecorder::RecordRasterEnd(const RasterCache* cache) { std::scoped_lock state_lock(state_mutex_); FML_DCHECK(state_ == State::kRasterStart); + FML_DCHECK(sweep_count_at_raster_start_ == + (cache ? cache->sweep_count() : -1)); state_ = State::kRasterEnd; raster_end_ = fml::TimePoint::Now(); raster_end_wall_time_ = fml::TimePoint::CurrentWallTime(); + if (cache) { + layer_cache_count_ = cache->GetLayerCachedEntriesCount(); + layer_cache_bytes_ = cache->EstimateLayerCacheByteSize(); + picture_cache_count_ = cache->GetPictureCachedEntriesCount(); + picture_cache_bytes_ = cache->EstimatePictureCacheByteSize(); + } else { + layer_cache_count_ = layer_cache_bytes_ = picture_cache_count_ = + picture_cache_bytes_ = 0; + } timing_.Set(FrameTiming::kVsyncStart, vsync_start_); timing_.Set(FrameTiming::kBuildStart, build_start_); timing_.Set(FrameTiming::kBuildFinish, build_end_); @@ -122,6 +163,8 @@ FrameTiming FrameTimingsRecorder::RecordRasterEnd() { timing_.Set(FrameTiming::kRasterFinish, raster_end_); timing_.Set(FrameTiming::kRasterFinishWallTime, raster_end_wall_time_); timing_.SetFrameNumber(GetFrameNumber()); + timing_.SetRasterCacheStatistics(layer_cache_count_, layer_cache_bytes_, + picture_cache_count_, picture_cache_bytes_); return timing_; } @@ -154,11 +197,16 @@ std::unique_ptr FrameTimingsRecorder::CloneUntil( if (state >= State::kRasterStart) { recorder->raster_start_ = raster_start_; + recorder->sweep_count_at_raster_start_ = sweep_count_at_raster_start_; } if (state >= State::kRasterEnd) { recorder->raster_end_ = raster_end_; recorder->raster_end_wall_time_ = raster_end_wall_time_; + recorder->layer_cache_count_ = layer_cache_count_; + recorder->layer_cache_bytes_ = layer_cache_bytes_; + recorder->picture_cache_count_ = picture_cache_count_; + recorder->picture_cache_bytes_ = picture_cache_bytes_; } return recorder; diff --git a/engine/src/flutter/flow/frame_timings.h b/engine/src/flutter/flow/frame_timings.h index a882a45db9..e79c4d0e5b 100644 --- a/engine/src/flutter/flow/frame_timings.h +++ b/engine/src/flutter/flow/frame_timings.h @@ -8,6 +8,7 @@ #include #include "flutter/common/settings.h" +#include "flutter/flow/raster_cache.h" #include "flutter/fml/macros.h" #include "flutter/fml/time/time_delta.h" #include "flutter/fml/time/time_point.h" @@ -70,6 +71,18 @@ class FrameTimingsRecorder { /// Duration of the frame build time. fml::TimeDelta GetBuildDuration() const; + /// Count of the layer cache entries + size_t GetLayerCacheCount() const; + + /// Total Bytes in all layer cache entries + size_t GetLayerCacheBytes() const; + + /// Count of the picture cache entries + size_t GetPictureCacheCount() const; + + /// Total Bytes in all picture cache entries + size_t GetPictureCacheBytes() const; + /// Records a vsync event. void RecordVsync(fml::TimePoint vsync_start, fml::TimePoint vsync_target); @@ -80,14 +93,15 @@ class FrameTimingsRecorder { void RecordBuildEnd(fml::TimePoint build_end); /// Records a raster start event. - void RecordRasterStart(fml::TimePoint raster_start); + void RecordRasterStart(fml::TimePoint raster_start, + const RasterCache* cache = nullptr); /// Clones the recorder until (and including) the specified state. std::unique_ptr CloneUntil(State state); /// Records a raster end event, and builds a `FrameTiming` that summarizes all /// the events. This summary is sent to the framework. - FrameTiming RecordRasterEnd(); + FrameTiming RecordRasterEnd(const RasterCache* cache = nullptr); /// Returns the frame number. Frame number is unique per frame and a frame /// built earlier will have a frame number less than a frame that has been @@ -117,6 +131,12 @@ class FrameTimingsRecorder { fml::TimePoint raster_end_; fml::TimePoint raster_end_wall_time_; + int sweep_count_at_raster_start_; + size_t layer_cache_count_; + size_t layer_cache_bytes_; + size_t picture_cache_count_; + size_t picture_cache_bytes_; + // Set when `RecordRasterEnd` is called. Cannot be reset once set. FrameTiming timing_; diff --git a/engine/src/flutter/flow/frame_timings_recorder_unittests.cc b/engine/src/flutter/flow/frame_timings_recorder_unittests.cc index 3cbb33ca97..525244cb72 100644 --- a/engine/src/flutter/flow/frame_timings_recorder_unittests.cc +++ b/engine/src/flutter/flow/frame_timings_recorder_unittests.cc @@ -3,6 +3,10 @@ // found in the LICENSE file. #include "flutter/flow/frame_timings.h" +#include "flutter/flow/testing/layer_test.h" +#include "flutter/flow/testing/mock_layer.h" +#include "flutter/flow/testing/mock_raster_cache.h" +#include "third_party/skia/include/core/SkPictureRecorder.h" #include @@ -66,12 +70,85 @@ TEST(FrameTimingsRecorderTest, RecordRasterTimes) { ASSERT_GT(recorder->GetRasterEndWallTime(), before_raster_end_wall_time); ASSERT_LT(recorder->GetRasterEndWallTime(), after_raster_end_wall_time); ASSERT_EQ(recorder->GetFrameNumber(), timing.GetFrameNumber()); + ASSERT_EQ(recorder->GetLayerCacheCount(), 0u); + ASSERT_EQ(recorder->GetLayerCacheBytes(), 0u); + ASSERT_EQ(recorder->GetPictureCacheCount(), 0u); + ASSERT_EQ(recorder->GetPictureCacheBytes(), 0u); +} + +TEST(FrameTimingsRecorderTest, RecordRasterTimesWithCache) { + auto recorder = std::make_unique(); + + const auto st = fml::TimePoint::Now(); + const auto en = st + fml::TimeDelta::FromMillisecondsF(16); + recorder->RecordVsync(st, en); + + const auto build_start = fml::TimePoint::Now(); + const auto build_end = build_start + fml::TimeDelta::FromMillisecondsF(16); + recorder->RecordBuildStart(build_start); + recorder->RecordBuildEnd(build_end); + + using namespace std::chrono_literals; + + MockRasterCache cache(1, 10); + cache.SweepAfterFrame(); + + const auto raster_start = fml::TimePoint::Now(); + recorder->RecordRasterStart(raster_start, &cache); + + cache.AddMockLayer(100, 100); + size_t layer_bytes = cache.EstimateLayerCacheByteSize(); + EXPECT_GT(layer_bytes, 0u); + cache.AddMockPicture(100, 100); + size_t picture_bytes = cache.EstimatePictureCacheByteSize(); + EXPECT_GT(picture_bytes, 0u); + + const auto before_raster_end_wall_time = fml::TimePoint::CurrentWallTime(); + std::this_thread::sleep_for(1ms); + const auto timing = recorder->RecordRasterEnd(&cache); + std::this_thread::sleep_for(1ms); + const auto after_raster_end_wall_time = fml::TimePoint::CurrentWallTime(); + + ASSERT_EQ(raster_start, recorder->GetRasterStartTime()); + ASSERT_GT(recorder->GetRasterEndWallTime(), before_raster_end_wall_time); + ASSERT_LT(recorder->GetRasterEndWallTime(), after_raster_end_wall_time); + ASSERT_EQ(recorder->GetFrameNumber(), timing.GetFrameNumber()); + ASSERT_EQ(recorder->GetLayerCacheCount(), 1u); + ASSERT_EQ(recorder->GetLayerCacheBytes(), layer_bytes); + ASSERT_EQ(recorder->GetPictureCacheCount(), 1u); + ASSERT_EQ(recorder->GetPictureCacheBytes(), picture_bytes); } // Windows and Fuchsia don't allow testing with killed by signal. #if !defined(OS_FUCHSIA) && !defined(OS_WIN) && \ (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG) +TEST(FrameTimingsRecorderTest, ThrowAfterUnexpectedCacheSweep) { + auto recorder = std::make_unique(); + + const auto st = fml::TimePoint::Now(); + const auto en = st + fml::TimeDelta::FromMillisecondsF(16); + recorder->RecordVsync(st, en); + + const auto build_start = fml::TimePoint::Now(); + const auto build_end = build_start + fml::TimeDelta::FromMillisecondsF(16); + recorder->RecordBuildStart(build_start); + recorder->RecordBuildEnd(build_end); + + using namespace std::chrono_literals; + + MockRasterCache cache; + + const auto raster_start = fml::TimePoint::Now(); + recorder->RecordRasterStart(raster_start, &cache); + std::this_thread::sleep_for(1ms); + cache.SweepAfterFrame(); + EXPECT_EXIT(recorder->RecordRasterEnd(&cache), + ::testing::KilledBySignal(SIGABRT), + "Check failed: sweep_count_at_raster_start_ == \\(cache \\? " + "cache->sweep_count\\(\\) : -1\\)."); +} + TEST(FrameTimingsRecorderTest, ThrowWhenRecordBuildBeforeVsync) { auto recorder = std::make_unique(); @@ -190,6 +267,45 @@ TEST(FrameTimingsRecorderTest, ClonedHasSameRasterEnd) { ASSERT_EQ(recorder->GetRasterStartTime(), cloned->GetRasterStartTime()); ASSERT_EQ(recorder->GetRasterEndTime(), cloned->GetRasterEndTime()); ASSERT_EQ(recorder->GetRasterEndWallTime(), cloned->GetRasterEndWallTime()); + ASSERT_EQ(recorder->GetLayerCacheCount(), cloned->GetLayerCacheCount()); + ASSERT_EQ(recorder->GetLayerCacheBytes(), cloned->GetLayerCacheBytes()); + ASSERT_EQ(recorder->GetPictureCacheCount(), cloned->GetPictureCacheCount()); + ASSERT_EQ(recorder->GetPictureCacheBytes(), cloned->GetPictureCacheBytes()); +} + +TEST(FrameTimingsRecorderTest, ClonedHasSameRasterEndWithCache) { + auto recorder = std::make_unique(); + MockRasterCache cache(1, 10); + cache.SweepAfterFrame(); + + const auto now = fml::TimePoint::Now(); + recorder->RecordVsync(now, now + fml::TimeDelta::FromMilliseconds(16)); + recorder->RecordBuildStart(fml::TimePoint::Now()); + recorder->RecordBuildEnd(fml::TimePoint::Now()); + recorder->RecordRasterStart(fml::TimePoint::Now(), &cache); + + cache.AddMockLayer(100, 100); + size_t layer_bytes = cache.EstimateLayerCacheByteSize(); + EXPECT_GT(layer_bytes, 0u); + cache.AddMockPicture(100, 100); + size_t picture_bytes = cache.EstimatePictureCacheByteSize(); + EXPECT_GT(picture_bytes, 0u); + + recorder->RecordRasterEnd(&cache); + + auto cloned = recorder->CloneUntil(FrameTimingsRecorder::State::kRasterEnd); + ASSERT_EQ(recorder->GetFrameNumber(), cloned->GetFrameNumber()); + ASSERT_EQ(recorder->GetVsyncStartTime(), cloned->GetVsyncStartTime()); + ASSERT_EQ(recorder->GetVsyncTargetTime(), cloned->GetVsyncTargetTime()); + ASSERT_EQ(recorder->GetBuildStartTime(), cloned->GetBuildStartTime()); + ASSERT_EQ(recorder->GetBuildEndTime(), cloned->GetBuildEndTime()); + ASSERT_EQ(recorder->GetRasterStartTime(), cloned->GetRasterStartTime()); + ASSERT_EQ(recorder->GetRasterEndTime(), cloned->GetRasterEndTime()); + ASSERT_EQ(recorder->GetRasterEndWallTime(), cloned->GetRasterEndWallTime()); + ASSERT_EQ(recorder->GetLayerCacheCount(), cloned->GetLayerCacheCount()); + ASSERT_EQ(recorder->GetLayerCacheBytes(), cloned->GetLayerCacheBytes()); + ASSERT_EQ(recorder->GetPictureCacheCount(), cloned->GetPictureCacheCount()); + ASSERT_EQ(recorder->GetPictureCacheBytes(), cloned->GetPictureCacheBytes()); } TEST(FrameTimingsRecorderTest, FrameNumberTraceArgIsValid) { diff --git a/engine/src/flutter/flow/raster_cache.cc b/engine/src/flutter/flow/raster_cache.cc index 7412bc46ac..18cd36d6f1 100644 --- a/engine/src/flutter/flow/raster_cache.cc +++ b/engine/src/flutter/flow/raster_cache.cc @@ -390,11 +390,12 @@ bool RasterCache::Draw(const Layer* layer, } void RasterCache::SweepAfterFrame() { + TraceStatsToTimeline(); SweepOneCacheAfterFrame(picture_cache_); SweepOneCacheAfterFrame(display_list_cache_); SweepOneCacheAfterFrame(layer_cache_); picture_cached_this_frame_ = 0; - TraceStatsToTimeline(); + sweep_count_++; } void RasterCache::Clear() { diff --git a/engine/src/flutter/flow/raster_cache.h b/engine/src/flutter/flow/raster_cache.h index 586dc3a413..8728f45471 100644 --- a/engine/src/flutter/flow/raster_cache.h +++ b/engine/src/flutter/flow/raster_cache.h @@ -207,6 +207,25 @@ class RasterCache { */ size_t EstimateLayerCacheByteSize() const; + /** + * @brief Return the count of cache sweeps that have occured. + * + * The sweep count will help to determine if a sweep of the cache may have + * removed expired entries since the last time the method was called. + * The count will increment even if the sweep performs no evictions. + */ + int sweep_count() const { return sweep_count_; } + + /** + * @brief Return the number of frames that a picture must be prepared + * before it will be cached. If the number is 0, then no picture will + * ever be cached. + * + * If the number is one, then it must be prepared and drawn on 1 frame + * and it will then be cached on the next frame if it is prepared. + */ + int access_threshold() const { return access_threshold_; } + private: struct Entry { bool used_this_frame = false; @@ -234,6 +253,7 @@ class RasterCache { const size_t access_threshold_; const size_t picture_cache_limit_per_frame_; size_t picture_cached_this_frame_ = 0; + int sweep_count_ = 0; mutable PictureRasterCacheKey::Map picture_cache_; mutable DisplayListRasterCacheKey::Map display_list_cache_; mutable LayerRasterCacheKey::Map layer_cache_; diff --git a/engine/src/flutter/flow/testing/mock_raster_cache.cc b/engine/src/flutter/flow/testing/mock_raster_cache.cc index 8fde780ad6..91b7b505fb 100644 --- a/engine/src/flutter/flow/testing/mock_raster_cache.cc +++ b/engine/src/flutter/flow/testing/mock_raster_cache.cc @@ -5,6 +5,7 @@ #include "flutter/flow/testing/mock_raster_cache.h" #include "flutter/flow/layers/layer.h" +#include "third_party/skia/include/core/SkPictureRecorder.h" namespace flutter { namespace testing { @@ -36,5 +37,32 @@ std::unique_ptr MockRasterCache::RasterizeLayer( return std::make_unique(cache_rect); } +void MockRasterCache::AddMockLayer(int width, int height) { + SkMatrix ctm = SkMatrix::I(); + SkPath path; + path.addRect(100, 100, 100 + width, 100 + height); + MockLayer layer = MockLayer(path); + layer.Preroll(&preroll_context_, ctm); + Prepare(&preroll_context_, &layer, ctm); +} + +void MockRasterCache::AddMockPicture(int width, int height) { + FML_DCHECK(access_threshold() > 0); + SkMatrix ctm = SkMatrix::I(); + SkPictureRecorder skp_recorder; + SkRTreeFactory rtree_factory; + SkPath path; + path.addRect(100, 100, 100 + width, 100 + height); + SkCanvas* recorder_canvas = skp_recorder.beginRecording( + SkRect::MakeLTRB(0, 0, 200 + width, 200 + height), &rtree_factory); + recorder_canvas->drawPath(path, SkPaint()); + sk_sp picture = skp_recorder.finishRecordingAsPicture(); + for (int i = 0; i < access_threshold(); i++) { + Prepare(nullptr, picture.get(), ctm, color_space_, true, false); + Draw(*picture, mock_canvas_); + } + Prepare(nullptr, picture.get(), ctm, color_space_, true, false); +} + } // namespace testing } // namespace flutter diff --git a/engine/src/flutter/flow/testing/mock_raster_cache.h b/engine/src/flutter/flow/testing/mock_raster_cache.h index 795963994f..428c37db78 100644 --- a/engine/src/flutter/flow/testing/mock_raster_cache.h +++ b/engine/src/flutter/flow/testing/mock_raster_cache.h @@ -6,6 +6,8 @@ #define FLOW_TESTING_MOCK_RASTER_CACHE_H_ #include "flutter/flow/raster_cache.h" +#include "flutter/flow/testing/mock_layer.h" +#include "flutter/testing/mock_canvas.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkPicture.h" @@ -44,6 +46,11 @@ class MockRasterCacheResult : public RasterCacheResult { */ class MockRasterCache : public RasterCache { public: + explicit MockRasterCache( + size_t access_threshold = 3, + size_t picture_cache_limit_per_frame = kDefaultPictureCacheLimitPerFrame) + : RasterCache(access_threshold, picture_cache_limit_per_frame) {} + std::unique_ptr RasterizePicture( SkPicture* picture, GrDirectContext* context, @@ -56,6 +63,33 @@ class MockRasterCache : public RasterCache { Layer* layer, const SkMatrix& ctm, bool checkerboard) const override; + + void AddMockLayer(int width, int height); + void AddMockPicture(int width, int height); + + private: + MockCanvas mock_canvas_; + SkColorSpace* color_space_ = mock_canvas_.imageInfo().colorSpace(); + MutatorsStack mutators_stack_; + Stopwatch raster_time_; + Stopwatch ui_time_; + TextureRegistry texture_registry_; + PrerollContext preroll_context_ = { + nullptr, /* raster_cache */ + nullptr, /* gr_context */ + nullptr, /* external_view_embedder */ + mutators_stack_, /* mutators_stack */ + color_space_, /* color_space */ + kGiantRect, /* cull_rect */ + false, /* layer reads from surface */ + raster_time_, /* raster stopwatch */ + ui_time_, /* frame build stopwatch */ + texture_registry_, /* texture_registry */ + false, /* checkerboard_offscreen_layers */ + 1.0f, /* frame_device_pixel_ratio */ + false, /* has_platform_view */ + false, /* has_texture_layer */ + }; }; } // namespace testing diff --git a/engine/src/flutter/lib/ui/platform_dispatcher.dart b/engine/src/flutter/lib/ui/platform_dispatcher.dart index 99a3bd3d77..cc0bdcdfb1 100644 --- a/engine/src/flutter/lib/ui/platform_dispatcher.dart +++ b/engine/src/flutter/lib/ui/platform_dispatcher.dart @@ -447,10 +447,10 @@ class PlatformDispatcher { // Called from the engine, via hooks.dart void _reportTimings(List timings) { - assert(timings.length % (FramePhase.values.length + 1) == 0); + assert(timings.length % FrameTiming._dataLength == 0); final List frameTimings = []; - for (int i = 0; i < timings.length; i += FramePhase.values.length + 1) { - frameTimings.add(FrameTiming._(timings.sublist(i, i + FramePhase.values.length + 1))); + for (int i = 0; i < timings.length; i += FrameTiming._dataLength) { + frameTimings.add(FrameTiming._(timings.sublist(i, i + FrameTiming._dataLength))); } _invoke1(onReportTimings, _onReportTimingsZone, frameTimings); } @@ -1180,6 +1180,23 @@ enum FramePhase { rasterFinishWallTime, } +enum _FrameTimingInfo { + /// The number of engine layers cached in the raster cache during the frame. + layerCacheCount, + + /// The number of bytes used to cache engine layers during the frame. + layerCacheBytes, + + /// The number of picture layers cached in the raster cache during the frame. + pictureCacheCount, + + /// The number of bytes used to cache pictures during the frame. + pictureCacheBytes, + + /// The frame number of the frame. + frameNumber, +} + /// Time-related performance metrics of a frame. /// /// If you're using the whole Flutter framework, please use @@ -1207,6 +1224,10 @@ class FrameTiming { required int rasterStart, required int rasterFinish, required int rasterFinishWallTime, + int layerCacheCount = 0, + int layerCacheBytes = 0, + int pictureCacheCount = 0, + int pictureCacheBytes = 0, int frameNumber = -1, }) { return FrameTiming._([ @@ -1216,10 +1237,16 @@ class FrameTiming { rasterStart, rasterFinish, rasterFinishWallTime, + layerCacheCount, + layerCacheBytes, + pictureCacheCount, + pictureCacheBytes, frameNumber, ]); } + static final int _dataLength = FramePhase.values.length + _FrameTimingInfo.values.length; + /// Construct [FrameTiming] with raw timestamps in microseconds. /// /// List [timestamps] must have the same number of elements as @@ -1227,14 +1254,16 @@ class FrameTiming { /// /// This constructor is usually only called by the Flutter engine, or a test. /// To get the [FrameTiming] of your app, see [PlatformDispatcher.onReportTimings]. - FrameTiming._(this._timestamps) - : assert(_timestamps.length == FramePhase.values.length + 1); + FrameTiming._(this._data) + : assert(_data.length == _dataLength); /// This is a raw timestamp in microseconds from some epoch. The epoch in all /// [FrameTiming] is the same, but it may not match [DateTime]'s epoch. - int timestampInMicroseconds(FramePhase phase) => _timestamps[phase.index]; + int timestampInMicroseconds(FramePhase phase) => _data[phase.index]; - Duration _rawDuration(FramePhase phase) => Duration(microseconds: _timestamps[phase.index]); + Duration _rawDuration(FramePhase phase) => Duration(microseconds: _data[phase.index]); + + int _rawInfo(_FrameTimingInfo info) => _data[FramePhase.values.length + info.index]; /// The duration to build the frame on the UI thread. /// @@ -1273,16 +1302,54 @@ class FrameTiming { /// See also [vsyncOverhead], [buildDuration] and [rasterDuration]. Duration get totalSpan => _rawDuration(FramePhase.rasterFinish) - _rawDuration(FramePhase.vsyncStart); - /// The frame key associated with this frame measurement. - int get frameNumber => _timestamps.last; + /// The number of layers stored in the raster cache during the frame. + /// + /// See also [layerCacheBytes], [pictureCacheCount] and [pictureCacheBytes]. + int get layerCacheCount => _rawInfo(_FrameTimingInfo.layerCacheCount); - final List _timestamps; // in microseconds + /// The number of bytes of image data used to cache layers during the frame. + /// + /// See also [layerCacheCount], [layerCacheMegabytes], [pictureCacheCount] and [pictureCacheBytes]. + int get layerCacheBytes => _rawInfo(_FrameTimingInfo.layerCacheBytes); + + /// The number of megabytes of image data used to cache layers during the frame. + /// + /// See also [layerCacheCount], [layerCacheBytes], [pictureCacheCount] and [pictureCacheBytes]. + double get layerCacheMegabytes => layerCacheBytes / 1024.0 / 1024.0; + + /// The number of pictures stored in the raster cache during the frame. + /// + /// See also [layerCacheCount], [layerCacheBytes] and [pictureCacheBytes]. + int get pictureCacheCount => _rawInfo(_FrameTimingInfo.pictureCacheCount); + + /// The number of bytes of image data used to cache pictures during the frame. + /// + /// See also [layerCacheCount], [layerCacheBytes], [pictureCacheCount] and [pictureCacheMegabytes]. + int get pictureCacheBytes => _rawInfo(_FrameTimingInfo.pictureCacheBytes); + + /// The number of megabytes of image data used to cache pictures during the frame. + /// + /// See also [layerCacheCount], [layerCacheBytes], [pictureCacheCount] and [pictureCacheBytes]. + double get pictureCacheMegabytes => pictureCacheBytes / 1024.0 / 1024.0; + + /// The frame key associated with this frame measurement. + int get frameNumber => _data.last; + + final List _data; // some elements in microseconds, some in bytes, some are counts String _formatMS(Duration duration) => '${duration.inMicroseconds * 0.001}ms'; @override String toString() { - return '$runtimeType(buildDuration: ${_formatMS(buildDuration)}, rasterDuration: ${_formatMS(rasterDuration)}, vsyncOverhead: ${_formatMS(vsyncOverhead)}, totalSpan: ${_formatMS(totalSpan)}, frameNumber: ${_timestamps.last})'; + return '$runtimeType(buildDuration: ${_formatMS(buildDuration)}, ' + 'rasterDuration: ${_formatMS(rasterDuration)}, ' + 'vsyncOverhead: ${_formatMS(vsyncOverhead)}, ' + 'totalSpan: ${_formatMS(totalSpan)}, ' + 'layerCacheCount: $layerCacheCount, ' + 'layerCacheBytes: $layerCacheBytes, ' + 'pictureCacheCount: $pictureCacheCount, ' + 'pictureCacheBytes: $pictureCacheBytes, ' + 'frameNumber: ${_data.last})'; } } diff --git a/engine/src/flutter/lib/ui/window/platform_configuration.h b/engine/src/flutter/lib/ui/window/platform_configuration.h index e5ec3070a1..8bba4bd675 100644 --- a/engine/src/flutter/lib/ui/window/platform_configuration.h +++ b/engine/src/flutter/lib/ui/window/platform_configuration.h @@ -390,12 +390,13 @@ class PlatformConfiguration final { /// /// @see `FrameTiming` /// - /// @param[in] timings Collection of `FrameTiming::kCount` * `n` timestamps - /// for `n` frames whose timings have not been reported - /// yet. A collection of integers is reported here for - /// easier conversions to Dart objects. The timestamps - /// are measured against the system monotonic clock - /// measured in microseconds. + /// @param[in] timings Collection of `FrameTiming::kStatisticsCount` * 'n' + /// values for `n` frames whose timings have not been + /// reported yet. Many of the values are timestamps, but + /// a collection of integers is reported here for easier + /// conversions to Dart objects. The timestamps are + /// measured against the system monotonic clock measured + /// in microseconds. /// void ReportTimings(std::vector timings); diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/platform_dispatcher.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/platform_dispatcher.dart index 8408c11865..568a727d2f 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/platform_dispatcher.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/platform_dispatcher.dart @@ -207,6 +207,14 @@ enum FramePhase { rasterFinishWallTime, } +enum _FrameTimingInfo { + layerCacheCount, + layerCacheBytes, + pictureCacheCount, + pictureCacheBytes, + frameNumber, +} + class FrameTiming { factory FrameTiming({ required int vsyncStart, @@ -215,6 +223,10 @@ class FrameTiming { required int rasterStart, required int rasterFinish, required int rasterFinishWallTime, + int layerCacheCount = 0, + int layerCacheBytes = 0, + int pictureCacheCount = 0, + int pictureCacheBytes = 0, int frameNumber = 1, }) { return FrameTiming._([ @@ -224,16 +236,24 @@ class FrameTiming { rasterStart, rasterFinish, rasterFinishWallTime, + layerCacheCount, + layerCacheBytes, + pictureCacheCount, + pictureCacheBytes, frameNumber, ]); } - FrameTiming._(this._timestamps) - : assert(_timestamps.length == FramePhase.values.length + 1); + static final int _dataLength = FramePhase.values.length + _FrameTimingInfo.values.length; - int timestampInMicroseconds(FramePhase phase) => _timestamps[phase.index]; + FrameTiming._(this._data) + : assert(_data.length == _dataLength); - Duration _rawDuration(FramePhase phase) => Duration(microseconds: _timestamps[phase.index]); + int timestampInMicroseconds(FramePhase phase) => _data[phase.index]; + + Duration _rawDuration(FramePhase phase) => Duration(microseconds: _data[phase.index]); + + int _rawInfo(_FrameTimingInfo info) => _data[FramePhase.values.length + info.index]; Duration get buildDuration => _rawDuration(FramePhase.buildFinish) - _rawDuration(FramePhase.buildStart); @@ -246,15 +266,35 @@ class FrameTiming { Duration get totalSpan => _rawDuration(FramePhase.rasterFinish) - _rawDuration(FramePhase.vsyncStart); - int get frameNumber => _timestamps.last; + int get layerCacheCount => _rawInfo(_FrameTimingInfo.layerCacheCount); - final List _timestamps; // in microseconds + int get layerCacheBytes => _rawInfo(_FrameTimingInfo.layerCacheBytes); + + double get layerCacheMegabytes => layerCacheBytes / 1024.0 / 1024.0; + + int get pictureCacheCount => _rawInfo(_FrameTimingInfo.pictureCacheCount); + + int get pictureCacheBytes => _rawInfo(_FrameTimingInfo.pictureCacheBytes); + + double get pictureCacheMegabytes => pictureCacheBytes / 1024.0 / 1024.0; + + int get frameNumber => _data.last; + + final List _data; // some elements in microseconds, some in bytes, some are counts String _formatMS(Duration duration) => '${duration.inMicroseconds * 0.001}ms'; @override String toString() { - return '$runtimeType(buildDuration: ${_formatMS(buildDuration)}, rasterDuration: ${_formatMS(rasterDuration)}, vsyncOverhead: ${_formatMS(vsyncOverhead)}, totalSpan: ${_formatMS(totalSpan)}, frameNumber: $frameNumber)'; + return '$runtimeType(buildDuration: ${_formatMS(buildDuration)}, ' + 'rasterDuration: ${_formatMS(rasterDuration)}, ' + 'vsyncOverhead: ${_formatMS(vsyncOverhead)}, ' + 'totalSpan: ${_formatMS(totalSpan)}, ' + 'layerCacheCount: $layerCacheCount, ' + 'layerCacheBytes: $layerCacheBytes, ' + 'pictureCacheCount: $pictureCacheCount, ' + 'pictureCacheBytes: $pictureCacheBytes, ' + 'frameNumber: ${_data.last})'; } } diff --git a/engine/src/flutter/lib/web_ui/test/frame_timings_common.dart b/engine/src/flutter/lib/web_ui/test/frame_timings_common.dart index 697373baf2..53d79e946b 100644 --- a/engine/src/flutter/lib/web_ui/test/frame_timings_common.dart +++ b/engine/src/flutter/lib/web_ui/test/frame_timings_common.dart @@ -41,5 +41,9 @@ Future runFrameTimingsTest() async { expect(timing.buildDuration, greaterThanOrEqualTo(Duration.zero)); expect(timing.rasterDuration, greaterThanOrEqualTo(Duration.zero)); expect(timing.totalSpan, greaterThanOrEqualTo(Duration.zero)); + expect(timing.layerCacheCount, equals(0)); + expect(timing.layerCacheBytes, equals(0)); + expect(timing.pictureCacheCount, equals(0)); + expect(timing.pictureCacheBytes, equals(0)); } } diff --git a/engine/src/flutter/shell/common/rasterizer.cc b/engine/src/flutter/shell/common/rasterizer.cc index fe399580ed..2c874019e2 100644 --- a/engine/src/flutter/shell/common/rasterizer.cc +++ b/engine/src/flutter/shell/common/rasterizer.cc @@ -143,7 +143,8 @@ void Rasterizer::DrawLastLayerTree( if (!last_layer_tree_ || !surface_) { return; } - frame_timings_recorder->RecordRasterStart(fml::TimePoint::Now()); + frame_timings_recorder->RecordRasterStart( + fml::TimePoint::Now(), &compositor_context_->raster_cache()); DrawToSurface(*frame_timings_recorder, *last_layer_tree_); } @@ -374,7 +375,8 @@ RasterStatus Rasterizer::DoDraw( return RasterStatus::kFailed; } - frame_timings_recorder->RecordRasterStart(fml::TimePoint::Now()); + frame_timings_recorder->RecordRasterStart( + fml::TimePoint::Now(), &compositor_context_->raster_cache()); PersistentCache* persistent_cache = PersistentCache::GetCacheForProcess(); persistent_cache->ResetStoredNewShaders(); @@ -547,7 +549,8 @@ RasterStatus Rasterizer::DrawToSurfaceUnsafe( frame->Submit(); } - frame_timings_recorder.RecordRasterEnd(); + frame_timings_recorder.RecordRasterEnd( + &compositor_context_->raster_cache()); FireNextFrameCallbackIfPresent(); if (surface_->GetContext()) { diff --git a/engine/src/flutter/shell/common/shell.cc b/engine/src/flutter/shell/common/shell.cc index 376524710d..f966618360 100644 --- a/engine/src/flutter/shell/common/shell.cc +++ b/engine/src/flutter/shell/common/shell.cc @@ -1368,8 +1368,8 @@ void Shell::ReportTimings() { size_t Shell::UnreportedFramesCount() const { // Check that this is running on the raster thread to avoid race conditions. FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); - FML_DCHECK(unreported_timings_.size() % (FrameTiming::kCount + 1) == 0); - return unreported_timings_.size() / (FrameTiming::kCount + 1); + FML_DCHECK(unreported_timings_.size() % (FrameTiming::kStatisticsCount) == 0); + return unreported_timings_.size() / (FrameTiming::kStatisticsCount); } void Shell::OnFrameRasterized(const FrameTiming& timing) { @@ -1386,11 +1386,18 @@ void Shell::OnFrameRasterized(const FrameTiming& timing) { return; } + size_t old_count = unreported_timings_.size(); for (auto phase : FrameTiming::kPhases) { unreported_timings_.push_back( timing.Get(phase).ToEpochDelta().ToMicroseconds()); } + unreported_timings_.push_back(timing.GetLayerCacheCount()); + unreported_timings_.push_back(timing.GetLayerCacheBytes()); + unreported_timings_.push_back(timing.GetPictureCacheCount()); + unreported_timings_.push_back(timing.GetPictureCacheBytes()); unreported_timings_.push_back(timing.GetFrameNumber()); + FML_DCHECK(unreported_timings_.size() == + old_count + FrameTiming::kStatisticsCount); // In tests using iPhone 6S with profile mode, sending a batch of 1 frame or a // batch of 100 frames have roughly the same cost of less than 0.1ms. Sending diff --git a/engine/src/flutter/testing/dart/window_test.dart b/engine/src/flutter/testing/dart/window_test.dart index 774f45d26c..66bcefa130 100644 --- a/engine/src/flutter/testing/dart/window_test.dart +++ b/engine/src/flutter/testing/dart/window_test.dart @@ -30,7 +30,42 @@ void main() { rasterFinishWallTime: 19501, frameNumber: 23, ); - expect(timing.toString(), 'FrameTiming(buildDuration: 7.0ms, rasterDuration: 10.5ms, vsyncOverhead: 0.5ms, totalSpan: 19.0ms, frameNumber: 23)'); + expect(timing.toString(), + 'FrameTiming(buildDuration: 7.0ms, ' + 'rasterDuration: 10.5ms, ' + 'vsyncOverhead: 0.5ms, ' + 'totalSpan: 19.0ms, ' + 'layerCacheCount: 0, ' + 'layerCacheBytes: 0, ' + 'pictureCacheCount: 0, ' + 'pictureCacheBytes: 0, ' + 'frameNumber: 23)'); + }); + + test('FrameTiming.toString with cache statistics has the correct format', () { + final FrameTiming timing = FrameTiming( + vsyncStart: 500, + buildStart: 1000, + buildFinish: 8000, + rasterStart: 9000, + rasterFinish: 19500, + rasterFinishWallTime: 19501, + layerCacheCount: 5, + layerCacheBytes: 200000, + pictureCacheCount: 3, + pictureCacheBytes: 300000, + frameNumber: 29, + ); + expect(timing.toString(), + 'FrameTiming(buildDuration: 7.0ms, ' + 'rasterDuration: 10.5ms, ' + 'vsyncOverhead: 0.5ms, ' + 'totalSpan: 19.0ms, ' + 'layerCacheCount: 5, ' + 'layerCacheBytes: 200000, ' + 'pictureCacheCount: 3, ' + 'pictureCacheBytes: 300000, ' + 'frameNumber: 29)'); }); test('computePlatformResolvedLocale basic', () {