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 #ifndef CHRE_UTIL_THROTTLE_H_ 18 #define CHRE_UTIL_THROTTLE_H_ 19 20 /** 21 * Throttles an action to a given interval and maximum number of times. 22 * The action will be called at most maxCount in every interval. 23 * 24 * @param action The action to throttle 25 * @param interval The interval between actions 26 * @param maxCount The maximum number of times to call the action 27 * @param getTime A function to get the current time 28 */ 29 #define CHRE_THROTTLE(action, interval, maxCount, getTime) \ 30 do { \ 31 static uint32_t _count = 0; \ 32 static bool _hasLastCallTime = false; \ 33 static Nanoseconds _lastCallTime; \ 34 Nanoseconds _now = getTime; \ 35 if (!_hasLastCallTime || _now - _lastCallTime >= interval) { \ 36 _hasLastCallTime = true; \ 37 _count = 0; \ 38 _lastCallTime = _now; \ 39 } \ 40 if (++_count > maxCount) { \ 41 break; \ 42 } \ 43 action; \ 44 } while (0) 45 46 #endif // CHRE_UTIL_THROTTLE_H_ 47