1 /* 2 * Copyright (C) 2024 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 #pragma once 18 19 #define ATRACE_TAG ATRACE_TAG_CAMERA 20 21 #include <utils/Trace.h> 22 23 #include <ctime> 24 #include <string> 25 26 class ScopedTrace final { 27 public: ScopedTrace(const std::string & name)28 explicit ScopedTrace(const std::string& name) : ScopedTrace(name, generateRandomInteger()) {} ScopedTrace(const std::string & name,int cookie)29 explicit ScopedTrace(const std::string& name, int cookie) : mName(name), mCookie(cookie) { 30 beginTrace(mName, mCookie); 31 } 32 ScopedTrace(const std::string & track,const std::string & name)33 explicit ScopedTrace(const std::string& track, const std::string& name) : 34 ScopedTrace(track, name, generateRandomInteger()) {} ScopedTrace(const std::string & track,const std::string & name,int cookie)35 explicit ScopedTrace(const std::string& track, const std::string& name, int cookie) : 36 mTrack(track), mName(name), mCookie(cookie), mHasTrack(true) { 37 beginTrace(mTrack, mName, mCookie); 38 } 39 ~ScopedTrace()40 ~ScopedTrace() { 41 if (mHasTrack) { 42 endTrace(mTrack, mName, mCookie); 43 } else { 44 endTrace(mName, mCookie); 45 } 46 } 47 48 // This should not be a copyable. 49 ScopedTrace(const ScopedTrace&) = delete; 50 ScopedTrace& operator=(const ScopedTrace&) = delete; 51 52 private: beginTrace(const std::string & name,int cookie)53 static void beginTrace(const std::string& name, int cookie) { 54 ATRACE_ASYNC_BEGIN(name.c_str(), cookie); 55 } 56 beginTrace(const std::string & track,const std::string & name,int cookie)57 static void beginTrace(const std::string& track, const std::string& name, int cookie) { 58 ATRACE_ASYNC_FOR_TRACK_BEGIN(track.c_str(), name.c_str(), cookie); 59 } 60 endTrace(const std::string & name,int cookie)61 static void endTrace(const std::string& name, int cookie) { 62 ATRACE_ASYNC_END(name.c_str(), cookie); 63 } 64 endTrace(const std::string & track,const std::string & name,int cookie)65 static void endTrace(const std::string& track, [[maybe_unused]] const std::string& name, 66 int cookie) { 67 ATRACE_ASYNC_FOR_TRACK_END(track.c_str(), cookie); 68 } 69 generateRandomInteger()70 static int generateRandomInteger() { 71 srand(time(nullptr)); 72 return rand(); 73 } 74 75 std::string mTrack; 76 std::string mName; 77 int mCookie; 78 bool mHasTrack = false; 79 }; 80