1 /*
2  * Copyright (C) 2022 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 #include <mutex>
20 #include <string>
21 
22 #include <android-base/thread_annotations.h>
23 
24 namespace android::mediautils {
25 
26 /**
27  * Collect Thread performance statistics.
28  *
29  * An onBegin() and onEnd() signal a continuous "run".
30  * Statistics are returned by toString().
31  */
32 class ThreadSnapshot {
33 public:
34     explicit ThreadSnapshot(pid_t tid = -1) { mState.reset(tid); };
35 
36     // Returns current tid
37     pid_t getTid() const;
38 
39     // Sets the tid
40     void setTid(pid_t tid);
41 
42     // Reset statistics, keep same tid.
43     void reset();
44 
45     // Signal a timing run is beginning
46     void onBegin();
47 
48     // Signal a timing run is ending
49     void onEnd();
50 
51     // Return the thread snapshot statistics in a string
52     std::string toString() const;
53 
54 private:
55     mutable std::mutex mLock;
56 
57     // State represents our statistics at a given point in time.
58     // It is not thread-safe, so any locking must occur at the caller.
59     struct State {
60         pid_t mTid;
61         int64_t mBeginTimeNs;  // when last run began
62         int64_t mEndTimeNs;    // when last run ends (if less than begin time, not started)
63         int64_t mCumulativeTimeNs;
64 
65         // Sched is the scheduler statistics obtained as a string.
66         // This is parsed only when toString() is called.
67         std::string mBeginSched;
68 
69         // Clears existing state.
70         void reset(pid_t tid);
71 
72         // onBegin() takes a std::string sched should can be captured outside
73         // of locking.
74         void onBegin(std::string sched);
75         void onEnd();
76         std::string toString() const;
77     };
78 
79     // Our current state. We only keep the current running state.
80     State mState GUARDED_BY(mLock);
81 };
82 
83 } // android::mediautils
84