Merge "Adjust performance test timings"
[cps.git] / integration-test / src / test / java / org / onap / cps / integration / ResourceMeter.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2023 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the 'License');
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an 'AS IS' BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.integration;
22
23 import org.springframework.util.StopWatch;
24
25 /**
26  * Time and memory stop watch, exposing total running time and memory used.
27  */
28 public class ResourceMeter {
29     private final StopWatch stopWatch = new StopWatch();
30     private long memoryUsedBefore;
31     private long memoryUsedAfter;
32
33     /**
34      * Start measurement.
35      */
36     public void start() {
37         System.gc();
38         memoryUsedBefore = getCurrentMemoryUsage();
39         stopWatch.start();
40     }
41
42     /**
43      * Stop measurement.
44      */
45     public void stop() {
46         stopWatch.stop();
47         memoryUsedAfter = getCurrentMemoryUsage();
48     }
49
50     /**
51      * Get the total time in seconds.
52      * @return total time in seconds
53      */
54     public double getTotalTimeInSeconds() {
55         return stopWatch.getTotalTimeSeconds();
56     }
57
58     /**
59      * Get the total memory used in megabytes.
60      * @return total memory used in megabytes
61      */
62     public double getTotalMemoryUsageInMB() {
63         return (memoryUsedAfter - memoryUsedBefore) / 1_000_000.0;
64     }
65
66     private static long getCurrentMemoryUsage() {
67         return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
68     }
69 }
70