• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2023 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  *      http://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 @file:OptIn(
18     androidx.benchmark.perfetto.ExperimentalPerfettoCaptureApi::class,
19     androidx.benchmark.traceprocessor.ExperimentalTraceProcessorApi::class,
20 )
21 
22 package android.tools.traces.parsers.perfetto
23 
24 import android.tools.io.TraceType
25 import android.tools.withTracing
26 import androidx.benchmark.traceprocessor.PerfettoTrace
27 import androidx.benchmark.traceprocessor.TraceProcessor
28 import androidx.benchmark.macro.runServer
29 import java.io.File
30 import java.io.FileOutputStream
31 
32 typealias Row = Map<String, Any?>
33 
34 class TraceProcessorSession(val session: TraceProcessor.Session) {
35 
querynull36     fun <T> query(sql: String, predicate: (List<Row>) -> T): T {
37         return withTracing("TraceProcessorSession#query") {
38             val rows = session.query(sql)
39             predicate(rows.toList())
40         }
41     }
42 
43     companion object {
44         @JvmStatic
loadPerfettoTracenull45         fun <T> loadPerfettoTrace(trace: ByteArray, predicate: (TraceProcessorSession) -> T): T {
46             return withTracing("TraceProcessorSession#loadPerfettoTrace") {
47                 val traceFile = File.createTempFile(TraceType.SF.fileName, "")
48                 FileOutputStream(traceFile).use { it.write(trace) }
49                 val result =
50                     TraceProcessor.runServer {
51                         loadTrace(PerfettoTrace(traceFile.absolutePath)) {
52                             predicate(TraceProcessorSession(this))
53                         }
54                     }
55                 result
56             }
57         }
58     }
59 }