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 #include "policy/cpu_policy.h"
16 #include "work_sched_hilog.h"
17 #include "cpu_collector.h"
18 
19 using namespace std;
20 
21 namespace OHOS {
22 namespace WorkScheduler {
23 const int32_t CPU_HIGH = 60;
24 const int32_t CPU_NORMAL = 50;
25 const int32_t CPU_LOW = 30;
26 const int32_t INIT_CPU = 0;
27 const int32_t COUNT_CPU_MAX = 0;
28 const int32_t COUNT_CPU_HIGH = 1;
29 const int32_t COUNT_CPU_NORMAL = 2;
30 const int32_t COUNT_CPU_LOW = 3;
31 const int32_t CPU_UPPER_LIMIT = 100;
32 const int32_t UNIT = 100;
33 
CpuPolicy(shared_ptr<WorkPolicyManager> workPolicyManager)34 CpuPolicy::CpuPolicy(shared_ptr<WorkPolicyManager> workPolicyManager)
35 {
36     workPolicyManager_ = workPolicyManager;
37 }
38 
~CpuPolicy()39 CpuPolicy::~CpuPolicy()
40 {
41 }
42 
GetCpuUsage()43 int32_t CpuPolicy::GetCpuUsage()
44 {
45     if (workPolicyManager_ != nullptr) {
46         int32_t dumpSetCpu = workPolicyManager_->GetDumpSetCpuUsage();
47         if (0 < dumpSetCpu && dumpSetCpu <= CPU_UPPER_LIMIT) {
48             WS_HILOGI("dump set cpu: %{public}d", dumpSetCpu);
49             return dumpSetCpu;
50         }
51     }
52     int32_t cpuUsage = INIT_CPU;
53     auto collector = OHOS::HiviewDFX::UCollectClient::CpuCollector::Create();
54     auto collectResult = collector->GetSysCpuUsage();
55     int32_t retCode = collectResult.retCode;
56     WS_HILOGD("retCode of collectResult: %{public}d", retCode);
57     if (retCode == OHOS::HiviewDFX::UCollect::UcError::SUCCESS) {
58         cpuUsage = static_cast<int>(collectResult.data * UNIT);
59     }
60     return cpuUsage;
61 }
62 
GetPolicyMaxRunning()63 int32_t CpuPolicy::GetPolicyMaxRunning()
64 {
65     int32_t cpuUsage = GetCpuUsage();
66     int32_t policyRes;
67     if (cpuUsage < CPU_LOW) {
68         policyRes = COUNT_CPU_LOW;
69     } else if (cpuUsage >= CPU_LOW && cpuUsage < CPU_NORMAL) {
70         policyRes = COUNT_CPU_NORMAL;
71     } else if (cpuUsage >= CPU_NORMAL && cpuUsage < CPU_HIGH) {
72         policyRes = COUNT_CPU_HIGH;
73     } else {
74         policyRes = COUNT_CPU_MAX;
75     }
76     WS_HILOGD("cpu_usage: %{public}d, policyRes: %{public}d", cpuUsage, policyRes);
77     return policyRes;
78 }
79 
GetPolicyName()80 std::string CpuPolicy::GetPolicyName()
81 {
82     return "CPU_POLICY";
83 }
84 } // namespace WorkScheduler
85 } // namespace OHOS