1 /* 2 * Copyright (C) 2011 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 _THREAD_CPU_USAGE_H 18 #define _THREAD_CPU_USAGE_H 19 20 #include <fcntl.h> 21 #include <pthread.h> 22 23 namespace android { 24 25 // Track CPU usage for the current thread. 26 // Units are in per-thread CPU ns, as reported by 27 // clock_gettime(CLOCK_THREAD_CPUTIME_ID). Simple usage: for cyclic 28 // threads where you want to measure the execution time of the whole 29 // cycle, just call sampleAndEnable() at the start of each cycle. 30 // For acyclic threads, or for cyclic threads where you want to measure/track 31 // only part of each cycle, call enable(), disable(), and/or setEnabled() 32 // to demarcate the region(s) of interest, and then call sample() periodically. 33 // This class is not thread-safe for concurrent calls from multiple threads; 34 // the methods of this class may only be called by the current thread 35 // which constructed the object. 36 37 class ThreadCpuUsage 38 { 39 40 public: 41 ThreadCpuUsage() : 42 mIsEnabled(false), 43 mWasEverEnabled(false), 44 mAccumulator(0), 45 // mPreviousTs 46 // mMonotonicTs 47 mMonotonicKnown(false) 48 { 49 (void) pthread_once(&sOnceControl, &init); 50 for (int i = 0; i < sKernelMax; ++i) { 51 mCurrentkHz[i] = (uint32_t) ~0; // unknown 52 } 53 } 54 55 ~ThreadCpuUsage() { } 56 57 // Return whether currently tracking CPU usage by current thread 58 bool isEnabled() const { return mIsEnabled; } 59 60 // Enable tracking of CPU usage by current thread; 61 // any CPU used from this point forward will be tracked. 62 // Returns the previous enabled status. 63 bool enable() { return setEnabled(true); } 64 65 // Disable tracking of CPU usage by current thread; 66 // any CPU used from this point forward will be ignored. 67 // Returns the previous enabled status. 68 bool disable() { return setEnabled(false); } 69 70 // Set the enabled status and return the previous enabled status. 71 // This method is intended to be used for safe nested enable/disabling. 72 bool setEnabled(bool isEnabled); 73 74 // Add a sample point, and also enable tracking if needed. 75 // If tracking has never been enabled, then this call enables tracking but 76 // does _not_ add a sample -- it is not possible to add a sample the 77 // first time because there is no previous point to subtract from. 78 // Otherwise, if tracking is enabled, 79 // then adds a sample for tracked CPU ns since the previous 80 // sample, or since the first call to sampleAndEnable(), enable(), or 81 // setEnabled(true). If there was a previous sample but tracking is 82 // now disabled, then adds a sample for the tracked CPU ns accumulated 83 // up until the most recent disable(), resets this accumulator, and then 84 // enables tracking. Calling this method rather than enable() followed 85 // by sample() avoids a race condition for the first sample. 86 // Returns true if the sample 'ns' is valid, or false if invalid. 87 // Note that 'ns' is an output parameter passed by reference. 88 // The caller does not need to initialize this variable. 89 // The units are CPU nanoseconds consumed by current thread. 90 bool sampleAndEnable(double& ns); 91 92 // Add a sample point, but do not 93 // change the tracking enabled status. If tracking has either never been 94 // enabled, or has never been enabled since the last sample, then log a warning 95 // and don't add sample. Otherwise, adds a sample for tracked CPU ns since 96 // the previous sample or since the first call to sampleAndEnable(), 97 // enable(), or setEnabled(true) if no previous sample. 98 // Returns true if the sample is valid, or false if invalid. 99 // Note that 'ns' is an output parameter passed by reference. 100 // The caller does not need to initialize this variable. 101 // The units are CPU nanoseconds consumed by current thread. 102 bool sample(double& ns); 103 104 // Return the elapsed delta wall clock ns since initial enable or reset, 105 // as reported by clock_gettime(CLOCK_MONOTONIC). 106 long long elapsed() const; 107 108 // Reset elapsed wall clock. Has no effect on tracking or accumulator. 109 void resetElapsed(); 110 111 // Return current clock frequency for specified CPU, in kHz. 112 // You can get your CPU number using sched_getcpu(2). Note that, unless CPU affinity 113 // has been configured appropriately, the CPU number can change. 114 // Also note that, unless the CPU governor has been configured appropriately, 115 // the CPU frequency can change. And even if the CPU frequency is locked down 116 // to a particular value, that the frequency might still be adjusted 117 // to prevent thermal overload. Therefore you should poll for your thread's 118 // current CPU number and clock frequency periodically. 119 uint32_t getCpukHz(int cpuNum); 120 121 private: 122 bool mIsEnabled; // whether tracking is currently enabled 123 bool mWasEverEnabled; // whether tracking was ever enabled 124 long long mAccumulator; // accumulated thread CPU time since last sample, in ns 125 struct timespec mPreviousTs; // most recent thread CPU time, valid only if mIsEnabled is true 126 struct timespec mMonotonicTs; // most recent monotonic time 127 bool mMonotonicKnown; // whether mMonotonicTs has been set 128 129 static const int MAX_CPU = 8; 130 static int sScalingFds[MAX_CPU];// file descriptor per CPU for reading scaling_cur_freq 131 uint32_t mCurrentkHz[MAX_CPU]; // current CPU frequency in kHz, not static to avoid a race 132 static pthread_once_t sOnceControl; 133 static int sKernelMax; // like MAX_CPU, but determined at runtime == cpu/kernel_max + 1 134 static void init(); // called once at first ThreadCpuUsage construction 135 static pthread_mutex_t sMutex; // protects sScalingFds[] after initialization 136 }; 137 138 } // namespace android 139 140 #endif // _THREAD_CPU_USAGE_H 141