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.util.concurrent.TimeUnit
24 import spock.lang.Specification
26 class ResourceMeterPerfTest extends Specification {
28 final int MEGABYTE = 1_000_000
30 def resourceMeter = new ResourceMeter()
32 def 'ResourceMeter accurately measures duration'() {
33 when: 'we measure how long a known operation takes'
35 TimeUnit.SECONDS.sleep(2)
37 then: 'ResourceMeter reports a duration within 10ms of the expected duration'
38 assert resourceMeter.getTotalTimeInSeconds() >= 2
39 assert resourceMeter.getTotalTimeInSeconds() <= 2.01
42 def 'ResourceMeter reports memory usage when allocating a large byte array'() {
43 when: 'the resource meter is started'
45 and: 'some memory is allocated'
46 byte[] array = new byte[50 * MEGABYTE]
47 and: 'the resource meter is stopped'
49 then: 'the reported memory usage is close to the amount of memory allocated'
50 assert resourceMeter.getTotalMemoryUsageInMB() >= 50
51 assert resourceMeter.getTotalMemoryUsageInMB() <= 55
54 def 'ResourceMeter measures PEAK memory usage when garbage collector runs'() {
55 when: 'the resource meter is started'
57 and: 'some memory is allocated'
58 byte[] array = new byte[50 * MEGABYTE]
59 and: 'the memory is garbage collected'
61 ResourceMeter.performGcAndWait()
62 and: 'the resource meter is stopped'
64 then: 'the reported memory usage is close to the peak amount of memory allocated'
65 assert resourceMeter.getTotalMemoryUsageInMB() >= 50
66 assert resourceMeter.getTotalMemoryUsageInMB() <= 55
69 def 'ResourceMeter measures memory increase only during measurement'() {
70 given: '50 megabytes is allocated before measurement'
71 byte[] arrayBefore = new byte[50 * MEGABYTE]
72 when: 'memory is allocated during measurement'
74 byte[] arrayDuring = new byte[40 * MEGABYTE]
76 and: '50 megabytes is allocated after measurement'
77 byte[] arrayAfter = new byte[50 * MEGABYTE]
78 then: 'the reported memory usage is close to the amount allocated DURING measurement'
79 assert resourceMeter.getTotalMemoryUsageInMB() >= 40
80 assert resourceMeter.getTotalMemoryUsageInMB() <= 45