1-- 2-- Copyright 2024 The Android Open Source Project 3-- 4-- Licensed under the Apache License, Version 2.0 (the "License"); 5-- you may not use this file except in compliance with the License. 6-- You may obtain a copy of the License at 7-- 8-- https://www.apache.org/licenses/LICENSE-2.0 9-- 10-- Unless required by applicable law or agreed to in writing, software 11-- distributed under the License is distributed on an "AS IS" BASIS, 12-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13-- See the License for the specific language governing permissions and 14-- limitations under the License. 15-- 16 17-- For a given counter timeline (e.g. a single counter track), returns 18-- intervals of time where the counter has the same value. 19-- 20-- Intervals are computed in a "forward-looking" way. That is, if a counter 21-- changes value at some timestamp, it's assumed it *just* reached that 22-- value and it should continue to have that value until the next 23-- value change. The final value is assumed to hold until the very end of 24-- the trace. 25-- 26-- For example, suppose we have the following data: 27-- ``` 28-- ts=0, value=10, track_id=1 29-- ts=0, value=10, track_id=2 30-- ts=10, value=10, track_id=1 31-- ts=10, value=20, track_id=2 32-- ts=20, value=30, track_id=1 33-- [end of trace at ts = 40] 34-- ``` 35-- 36-- Then this macro will generate the following intervals: 37-- ``` 38-- ts=0, dur=20, value=10, track_id=1 39-- ts=20, dur=10, value=30, track_id=1 40-- ts=0, dur=10, value=10, track_id=2 41-- ts=10, dur=30, value=20, track_id=2 42-- ``` 43CREATE PERFETTO MACRO counter_leading_intervals( 44 -- A table/view/subquery corresponding to a "counter-like" table. 45 -- This table must have the columns "id" and "ts" and "track_id" and "value" corresponding 46 -- to an id, timestamp, counter track_id and associated counter value. 47 counter_table TableOrSubquery) 48-- Table with the schema (id UINT32, ts UINT64, dur UINT64, track_id UINT64, 49-- value DOUBLE, next_value DOUBLE, delta_value DOUBLE). 50RETURNS TableOrSubquery AS 51( 52 WITH base AS ( 53 SELECT 54 id, 55 ts, 56 track_id, 57 value, 58 LAG(value) OVER (PARTITION BY track_id ORDER BY ts) AS lag_value 59 FROM $counter_table 60 ) 61 SELECT 62 id, 63 ts, 64 LEAD(ts, 1, trace_end()) OVER(PARTITION BY track_id ORDER BY ts) - ts AS dur, 65 track_id, 66 value, 67 LEAD(value) OVER(PARTITION BY track_id ORDER BY ts) AS next_value, 68 value - lag_value AS delta_value 69 FROM base 70 WHERE value != lag_value OR lag_value IS NULL 71);