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 "ecmascript/mem/mem_controller_utils.h"
17 
18 #include "ecmascript/mem/mem_common.h"
19 
20 namespace panda::ecmascript {
21 
CalculateAverageSpeed(const base::GCRingBuffer<BytesAndDuration, LENGTH> &buffer)22 double MemControllerUtils::CalculateAverageSpeed(const base::GCRingBuffer<BytesAndDuration, LENGTH> &buffer)
23 {
24     return CalculateAverageSpeed(buffer, MakeBytesAndDuration(0, 0), 0);
25 }
26 
CalculateAverageSpeed(const base::GCRingBuffer<BytesAndDuration, LENGTH> &buffer, const BytesAndDuration &initial, const double timeMs)27 double MemControllerUtils::CalculateAverageSpeed(const base::GCRingBuffer<BytesAndDuration, LENGTH> &buffer,
28     const BytesAndDuration &initial, const double timeMs)
29 {
30     BytesAndDuration sum = buffer.Sum(
31         [timeMs](BytesAndDuration a, BytesAndDuration b) {
32             if (timeMs != 0 && a.second >= timeMs) {
33                 return a;
34             }
35             return std::make_pair(a.first + b.first, a.second + b.second);
36         },
37         initial);
38     uint64_t bytes = sum.first;
39     double durations = sum.second;
40     if (fabs(durations) <= 1e-6) {
41         return 0;
42     }
43     double speed = bytes / durations;
44     const int maxSpeed = static_cast<int>(1_GB);
45     const int minSpeed = 1;
46     if (speed >= maxSpeed) {
47         return maxSpeed;
48     }
49     if (speed <= minSpeed) {
50         return minSpeed;
51     }
52     return speed;
53 }
54 
55 }