Merge "tp: CPU state breakdowns" into main
diff --git a/src/trace_processor/perfetto_sql/stdlib/sched/time_in_state.sql b/src/trace_processor/perfetto_sql/stdlib/sched/time_in_state.sql
index 8c6bc87..a12a95a 100644
--- a/src/trace_processor/perfetto_sql/stdlib/sched/time_in_state.sql
+++ b/src/trace_processor/perfetto_sql/stdlib/sched/time_in_state.sql
@@ -164,5 +164,32 @@
 GROUP BY 1, 2, 3, 4
 ORDER BY 5 DESC;
 
+-- Time spent by CPU in each scheduling state in a provided interval.
+CREATE PERFETTO FUNCTION sched_time_in_state_for_cpu_in_interval(
+    -- CPU id.
+    cpu INT,
+    -- Interval start.
+    ts INT,
+    -- Interval duration.
+    dur INT
+) RETURNS TABLE (
+    -- End state. From `sched.end_state`.
+    end_state STRING,
+    -- Duration in state.
+    dur INT
+) AS
+WITH sched_for_cpu AS (
+  SELECT id, ts, dur
+  FROM sched
+  WHERE cpu = $cpu AND dur != -1
+)
+SELECT
+    end_state,
+    sum(ii.dur) AS dur
+FROM sched
+JOIN _interval_intersect_single!($ts, $dur, sched_for_cpu) ii
+USING (id)
+GROUP BY end_state;
+
 
 
diff --git a/test/trace_processor/diff_tests/stdlib/sched/tests.py b/test/trace_processor/diff_tests/stdlib/sched/tests.py
index 6fd4414..bb24f1b 100644
--- a/test/trace_processor/diff_tests/stdlib/sched/tests.py
+++ b/test/trace_processor/diff_tests/stdlib/sched/tests.py
@@ -245,3 +245,21 @@
         "D","[NULL]","[NULL]","[NULL]",563645
         "R+","[NULL]","[NULL]","[NULL]",380156
         """))
+
+  def test_sched_time_in_state_for_cpu_in_interval(self):
+    return DiffTestBlueprint(
+        trace=DataPath('example_android_trace_30s.pb'),
+        query="""
+      INCLUDE PERFETTO MODULE sched.time_in_state;
+      SELECT * FROM
+      sched_time_in_state_for_cpu_in_interval(1, TRACE_START(), TRACE_DUR());
+      """,
+        out=Csv("""
+        "end_state","dur"
+        "D",311982601
+        "DK",31103960
+        "R",23230879715
+        "R+",1148673560
+        "S",3868233011
+        "x",35240577
+      """))