1 /* 2 * Copyright (C) 2016 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 #ifndef ART_LIBARTBASE_BASE_SYSTRACE_H_ 18 #define ART_LIBARTBASE_BASE_SYSTRACE_H_ 19 20 #define ATRACE_TAG ATRACE_TAG_DALVIK 21 #include <cutils/trace.h> 22 23 #include <sstream> 24 #include <string> 25 26 #include "android-base/stringprintf.h" 27 28 namespace art { 29 30 class ScopedTrace { 31 public: ScopedTrace(const char * name)32 explicit ScopedTrace(const char* name) { 33 ATRACE_BEGIN(name); 34 } 35 template <typename Fn> ScopedTrace(Fn fn)36 explicit ScopedTrace(Fn fn) { 37 if (ATRACE_ENABLED()) { 38 ATRACE_BEGIN(fn().c_str()); 39 } 40 } 41 ScopedTrace(const std::string & name)42 explicit ScopedTrace(const std::string& name) : ScopedTrace(name.c_str()) {} 43 ~ScopedTrace()44 ~ScopedTrace() { 45 ATRACE_END(); 46 } 47 }; 48 49 // Helper for the SCOPED_TRACE macro. Do not use directly. 50 class ScopedTraceNoStart { 51 public: ScopedTraceNoStart()52 ScopedTraceNoStart() { 53 } 54 ~ScopedTraceNoStart()55 ~ScopedTraceNoStart() { 56 ATRACE_END(); 57 } 58 59 // Message helper for the macro. Do not use directly. 60 class ScopedTraceMessageHelper { 61 public: ScopedTraceMessageHelper()62 ScopedTraceMessageHelper() { 63 } ~ScopedTraceMessageHelper()64 ~ScopedTraceMessageHelper() { 65 ATRACE_BEGIN(buffer_.str().c_str()); 66 } 67 stream()68 std::ostream& stream() { 69 return buffer_; 70 } 71 72 private: 73 std::ostringstream buffer_; 74 }; 75 }; 76 77 #define SCOPED_TRACE \ 78 ::art::ScopedTraceNoStart trace ## __LINE__; \ 79 (ATRACE_ENABLED()) && ::art::ScopedTraceNoStart::ScopedTraceMessageHelper().stream() 80 81 } // namespace art 82 83 #endif // ART_LIBARTBASE_BASE_SYSTRACE_H_ 84