1 /* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef PERFORMANCE_UTILS_H 17 #define PERFORMANCE_UTILS_H 18 19 #include <chrono> 20 #include <cstdint> 21 #include <limits> 22 #include <memory> 23 #include <mutex> 24 #include <algorithm> 25 26 #include "media_core.h" 27 #include "plugin/plugin_time.h" 28 29 namespace OHOS { 30 namespace Media { 31 namespace { 32 constexpr size_t DEFAULT_CAPACITY = 30; 33 constexpr int32_t MIN_SIZE = 1; 34 } 35 #define CALC_EXPR_TIME_MS(expr) \ 36 ({ \ 37 int64_t defaultDuration = 1; \ 38 auto start = std::chrono::high_resolution_clock::now(); \ 39 expr; \ 40 auto end = std::chrono::high_resolution_clock::now(); \ 41 int64_t duration = \ 42 static_cast<int64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()); \ 43 std::max(defaultDuration, duration); \ 44 }) 45 46 struct MainPerfData { 47 int32_t max = 0; 48 int32_t min = 0; 49 int32_t avg = 0; 50 }; 51 52 class PerfRecorder { 53 public: 54 PerfRecorder() = default; 55 PerfRecorder(int32_t capacity)56 PerfRecorder(int32_t capacity) : capacity_(std::max(MIN_SIZE, capacity)) {} 57 Record(int32_t extra)58 virtual bool Record(int32_t extra) 59 { 60 std::lock_guard<std::mutex> lock(mutex_); 61 int64_t time = Plugins::GetCurrentMillisecond(); 62 std::pair<int64_t, int32_t> pair = { time, extra }; 63 bool isFull = list_.size() >= capacity_; 64 if (isFull) { 65 list_.pop_front(); 66 } 67 list_.push_back(pair); 68 return isFull; 69 } 70 Reset()71 virtual void Reset() 72 { 73 std::lock_guard<std::mutex> lock(mutex_); 74 list_.clear(); 75 } 76 GetMainPerfData()77 virtual MainPerfData GetMainPerfData() 78 { 79 std::lock_guard<std::mutex> lock(mutex_); 80 int32_t total = 0; 81 int32_t max = std::numeric_limits<int32_t>::min(); 82 int32_t min = std::numeric_limits<int32_t>::max(); 83 84 for (auto pair : list_) { 85 total += pair.second; 86 max = std::max(max, pair.second); 87 min = std::min(min, pair.second); 88 } 89 int32_t avg = total / std::max(static_cast<int32_t>(list_.size()), MIN_SIZE); 90 91 return { .max = max, .min = min, .avg = avg }; 92 } 93 94 static const bool FULL = true; 95 96 protected: 97 std::mutex mutex_{}; 98 size_t capacity_{ DEFAULT_CAPACITY }; 99 std::list<std::pair<int64_t, int32_t>> list_ {}; 100 }; 101 102 } // namespace Media 103 } // namespace OHOS 104 #endif // PERFORMANCE_UTILS_H 105