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 <condition_variable>
23 #include <fstream>
24 #include <thread>
25
26 class Observer : public perfetto::TrackEventSessionObserver {
27 public:
Observer()28 Observer() { perfetto::TrackEvent::AddSessionObserver(this); }
~Observer()29 ~Observer() { perfetto::TrackEvent::RemoveSessionObserver(this); }
30
OnStart(const perfetto::DataSourceBase::StartArgs &)31 void OnStart(const perfetto::DataSourceBase::StartArgs&) override {
32 std::unique_lock<std::mutex> lock(mutex);
33 cv.notify_one();
34 }
35
WaitForTracingStart()36 void WaitForTracingStart() {
37 PERFETTO_LOG("Waiting for tracing to start...");
38 std::unique_lock<std::mutex> lock(mutex);
39 cv.wait(lock, [] { return perfetto::TrackEvent::IsEnabled(); });
40 PERFETTO_LOG("Tracing started");
41 }
42
43 std::mutex mutex;
44 std::condition_variable cv;
45 };
46
InitializePerfetto()47 void InitializePerfetto() {
48 perfetto::TracingInitArgs args;
49 // The backends determine where trace events are recorded. For this example we
50 // are going to use the system-wide tracing service, so that we can see our
51 // app's events in context with system profiling information.
52 args.backends = perfetto::kSystemBackend;
53
54 perfetto::Tracing::Initialize(args);
55 perfetto::TrackEvent::Register();
56 }
57
DrawPlayer(int player_number)58 void DrawPlayer(int player_number) {
59 TRACE_EVENT("rendering", "DrawPlayer", "player_number", player_number);
60 // Sleep to simulate a long computation.
61 std::this_thread::sleep_for(std::chrono::milliseconds(500));
62 }
63
DrawGame()64 void DrawGame() {
65 TRACE_EVENT("rendering", "DrawGame");
66 DrawPlayer(1);
67 DrawPlayer(2);
68 }
69
main(int,const char **)70 int main(int, const char**) {
71 InitializePerfetto();
72
73 Observer observer;
74 observer.WaitForTracingStart();
75
76 // Simulate some work that emits trace events.
77 // Note that we don't start and stop tracing here; for system-wide tracing
78 // this needs to be done through the "perfetto" command line tool or the
79 // Perfetto UI (https://ui.perfetto.dev).
80 DrawGame();
81
82 // Make sure the last event is closed for this example.
83 perfetto::TrackEvent::Flush();
84
85 return 0;
86 }
87