1 /*
2 * Copyright (c) 2024 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 #include "sys_cpu_usage_collector.h"
17
18 #include "hiview_logger.h"
19 #include "time_util.h"
20
21 namespace OHOS {
22 namespace HiviewDFX {
23 namespace UCollectUtil {
24 DEFINE_LOG_TAG("CpuCollector");
SysCpuUsageCollector(std::shared_ptr<CpuCalculator> cpuCalculator)25 SysCpuUsageCollector::SysCpuUsageCollector(std::shared_ptr<CpuCalculator> cpuCalculator) : cpuCalculator_(cpuCalculator)
26 {
27 // init sys cpu usage infos
28 (void)CollectSysCpuUsage(true);
29 }
30
CollectSysCpuUsage(bool isNeedUpdate)31 CollectResult<SysCpuUsage> SysCpuUsageCollector::CollectSysCpuUsage(bool isNeedUpdate)
32 {
33 CollectResult<SysCpuUsage> result;
34 std::vector<CpuTimeInfo> currCpuTimeInfos;
35 result.retCode = CpuUtil::GetCpuTimeInfos(currCpuTimeInfos);
36 if (result.retCode != UCollect::UcError::SUCCESS) {
37 return result;
38 }
39 SysCpuUsage& sysCpuUsage = result.data;
40 sysCpuUsage.startTime = lastSysCpuUsageTime_;
41 sysCpuUsage.endTime = TimeUtil::GetMilliseconds();
42 CalculateSysCpuUsageInfos(sysCpuUsage.cpuInfos, currCpuTimeInfos);
43 if (isNeedUpdate) {
44 lastSysCpuUsageTime_ = sysCpuUsage.endTime;
45 lastSysCpuTimeInfos_ = currCpuTimeInfos;
46 }
47 HIVIEW_LOGD("collect system cpu usage, size=%{public}zu, isNeedUpdate=%{public}d",
48 sysCpuUsage.cpuInfos.size(), isNeedUpdate);
49 return result;
50 }
51
CalculateSysCpuUsageInfos(std::vector<CpuUsageInfo> & cpuInfos,const std::vector<CpuTimeInfo> & currCpuTimeInfos)52 void SysCpuUsageCollector::CalculateSysCpuUsageInfos(std::vector<CpuUsageInfo>& cpuInfos,
53 const std::vector<CpuTimeInfo>& currCpuTimeInfos)
54 {
55 if (cpuCalculator_ == nullptr || currCpuTimeInfos.size() != lastSysCpuTimeInfos_.size()) {
56 return;
57 }
58 for (size_t i = 0; i < currCpuTimeInfos.size(); ++i) {
59 cpuInfos.emplace_back(cpuCalculator_->CalculateSysCpuUsageInfo(currCpuTimeInfos[i],
60 lastSysCpuTimeInfos_[i]));
61 }
62 }
63 } // UCollectUtil
64 } // HiViewDFX
65 } // OHOS
66