• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 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 // This example demonstrates system-wide tracing with Perfetto.
18 
19 #include "trace_categories.h"
20 
21 #include <chrono>
22 #include <fstream>
23 #include <thread>
24 
InitializePerfetto()25 void InitializePerfetto() {
26   perfetto::TracingInitArgs args;
27   // The backends determine where trace events are recorded. For this example we
28   // are going to use the system-wide tracing service, so that we can see our
29   // app's events in context with system profiling information.
30   args.backends = perfetto::kSystemBackend;
31 
32   perfetto::Tracing::Initialize(args);
33   perfetto::TrackEvent::Register();
34 }
35 
WaitForTracingStart()36 void WaitForTracingStart() {
37   PERFETTO_LOG("Waiting for tracing to start...");
38   while (!TRACE_EVENT_CATEGORY_ENABLED("rendering")) {
39     std::this_thread::sleep_for(std::chrono::milliseconds(100));
40   }
41   PERFETTO_LOG("Tracing started");
42 }
43 
DrawPlayer(int player_number)44 void DrawPlayer(int player_number) {
45   TRACE_EVENT("rendering", "DrawPlayer", "player_number", player_number);
46   // Sleep to simulate a long computation.
47   std::this_thread::sleep_for(std::chrono::milliseconds(500));
48 }
49 
DrawGame()50 void DrawGame() {
51   TRACE_EVENT("rendering", "DrawGame");
52   DrawPlayer(1);
53   DrawPlayer(2);
54 }
55 
main(int,const char **)56 int main(int, const char**) {
57   InitializePerfetto();
58   WaitForTracingStart();
59 
60   // Simulate some work that emits trace events.
61   // Note that we don't start and stop tracing here; for system-wide tracing
62   // this needs to be done through the "perfetto" command line tool or the
63   // Perfetto UI (https://ui.perfetto.dev).
64   DrawGame();
65 
66   // Make sure the last event is closed for this example.
67   perfetto::TrackEvent::Flush();
68 
69   return 0;
70 }
71