1 /*
2 * Copyright 2019 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 #include <android-base/stringprintf.h>
19 #include <cutils/compiler.h>
20 #include <utils/Trace.h>
21 #include <cmath>
22 #include <string>
23
24 namespace std {
25 template <class Rep, class Period>
signbit(std::chrono::duration<Rep,Period> v)26 bool signbit(std::chrono::duration<Rep, Period> v) {
27 return signbit(std::chrono::duration_cast<std::chrono::nanoseconds>(v).count());
28 }
29 } // namespace std
30
31 namespace android {
32
33 namespace {
34 template <typename T>
to_int64(T v)35 int64_t to_int64(T v) {
36 return int64_t(v);
37 }
38
39 template <class Rep, class Period>
to_int64(std::chrono::duration<Rep,Period> v)40 int64_t to_int64(std::chrono::duration<Rep, Period> v) {
41 return int64_t(v.count());
42 }
43 } // namespace
44
45 template <typename T>
46 class TracedOrdinal {
47 public:
48 static_assert(std::is_same<bool, T>() || (std::is_signed<T>() && std::is_integral<T>()) ||
49 std::is_same<std::chrono::nanoseconds, T>(),
50 "Type is not supported. Please test it with systrace before adding "
51 "it to the list.");
52
TracedOrdinal(std::string name,T initialValue)53 TracedOrdinal(std::string name, T initialValue)
54 : mName(std::move(name)),
55 mHasGoneNegative(std::signbit(initialValue)),
56 mData(initialValue) {
57 trace();
58 }
59
get()60 T get() const { return mData; }
61
T()62 operator T() const { return get(); }
63
64 TracedOrdinal& operator=(T other) {
65 mData = other;
66 mHasGoneNegative = mHasGoneNegative || std::signbit(mData);
67 trace();
68 return *this;
69 }
70
71 private:
trace()72 void trace() {
73 if (CC_LIKELY(!ATRACE_ENABLED())) {
74 return;
75 }
76
77 if (mNameNegative.empty()) {
78 mNameNegative = base::StringPrintf("%sNegative", mName.c_str());
79 }
80
81 if (!std::signbit(mData)) {
82 ATRACE_INT64(mName.c_str(), to_int64(mData));
83 if (mHasGoneNegative) {
84 ATRACE_INT64(mNameNegative.c_str(), 0);
85 }
86 } else {
87 ATRACE_INT64(mNameNegative.c_str(), -to_int64(mData));
88 ATRACE_INT64(mName.c_str(), 0);
89 }
90 }
91
92 const std::string mName;
93 std::string mNameNegative;
94 bool mHasGoneNegative;
95 T mData;
96 };
97
98 } // namespace android
99