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 shows how to log trace events to the console using the console
18 // interceptor.
19 
20 #include "trace_categories.h"
21 
22 #include <chrono>
23 #include <thread>
24 
InitializePerfetto()25 void InitializePerfetto() {
26   perfetto::TracingInitArgs args;
27   args.backends = perfetto::kInProcessBackend;
28   perfetto::Tracing::Initialize(args);
29   perfetto::TrackEvent::Register();
30   perfetto::ConsoleInterceptor::Register();
31 }
32 
StartTracing()33 std::unique_ptr<perfetto::TracingSession> StartTracing() {
34   perfetto::TraceConfig cfg;
35   cfg.add_buffers()->set_size_kb(1024);
36   auto* ds_cfg = cfg.add_data_sources()->mutable_config();
37   ds_cfg->set_name("track_event");
38 
39   // Enable the console interceptor.
40   ds_cfg->mutable_interceptor_config()->set_name("console");
41 
42   auto tracing_session = perfetto::Tracing::NewTrace();
43   tracing_session->Setup(cfg);
44   tracing_session->StartBlocking();
45   return tracing_session;
46 }
47 
DrawPlayer(int player_number)48 void DrawPlayer(int player_number) {
49   TRACE_EVENT("rendering", "DrawPlayer", "player_number", player_number);
50   // Sleep to simulate a long computation.
51   std::this_thread::sleep_for(std::chrono::milliseconds(500));
52 }
53 
DrawGame()54 void DrawGame() {
55   // This is an example of an unscoped slice, which begins and ends at specific
56   // points (instead of at the end of the current block scope).
57   TRACE_EVENT_BEGIN("rendering", "DrawGame");
58   DrawPlayer(1);
59   DrawPlayer(2);
60   TRACE_EVENT_END("rendering");
61 }
62 
main(int,const char **)63 int main(int, const char**) {
64   InitializePerfetto();
65   auto tracing_session = StartTracing();
66 
67   // Simulate some work that emits trace events.
68   DrawGame();
69 
70   tracing_session->StopBlocking();
71   return 0;
72 }
73