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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.cps.integration;
23 import java.lang.management.GarbageCollectorMXBean;
24 import java.lang.management.ManagementFactory;
25 import java.lang.management.MemoryPoolMXBean;
26 import java.lang.management.MemoryType;
27 import org.springframework.util.StopWatch;
30 * Time and memory stop watch, exposing total running time and memory used.
32 public class ResourceMeter {
33 private final StopWatch stopWatch = new StopWatch();
34 private long memoryUsedBefore;
35 private long memoryUsedAfter;
43 memoryUsedBefore = getPeakHeapUsage();
52 memoryUsedAfter = getPeakHeapUsage();
56 * Get the total time in seconds.
57 * @return total time in seconds
59 public double getTotalTimeInSeconds() {
60 return stopWatch.getTotalTimeSeconds();
64 * Get the total memory used in megabytes.
65 * @return total memory used in megabytes
67 public double getTotalMemoryUsageInMB() {
68 return (memoryUsedAfter - memoryUsedBefore) / 1_000_000.0;
71 static void performGcAndWait() {
72 final long gcCountBefore = getGcCount();
74 while (getGcCount() == gcCountBefore) {}
77 private static long getGcCount() {
78 return ManagementFactory.getGarbageCollectorMXBeans().stream()
79 .mapToLong(GarbageCollectorMXBean::getCollectionCount)
80 .filter(gcCount -> gcCount != -1)
84 private static long getPeakHeapUsage() {
85 return ManagementFactory.getMemoryPoolMXBeans().stream()
86 .filter(pool -> pool.getType() == MemoryType.HEAP)
87 .mapToLong(pool -> pool.getPeakUsage().getUsed())
91 private static void resetPeakHeapUsage() {
92 ManagementFactory.getMemoryPoolMXBeans().stream()
93 .filter(pool -> pool.getType() == MemoryType.HEAP)
94 .forEach(MemoryPoolMXBean::resetPeakUsage);