2 * ============LICENSE_START=======================================================
3 * dcaegen2-collectors-veshv
4 * ================================================================================
5 * Copyright (C) 2018 NOKIA
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
20 package org.onap.dcae.collectors.veshv.main
22 import org.jetbrains.spek.api.Spek
23 import org.jetbrains.spek.api.dsl.describe
24 import org.jetbrains.spek.api.dsl.it
25 import org.jetbrains.spek.api.dsl.xdescribe
26 import java.nio.ByteBuffer
28 object NioBuffersTest : Spek({
30 fun Int.toKibibytes(): Int = this * 1024
31 fun Int.toMebibytes(): Int = this * 1024 * 1024
33 val BUFFER_SIZES = listOf(128.toKibibytes(), 512.toKibibytes(), 1.toMebibytes(), 2.toMebibytes())
34 val NUMBER_OF_ITERATIONS = 100
36 fun measureCopyTimeInNanos(bb1: ByteBuffer, bb2: ByteBuffer): Double {
39 val start = System.nanoTime()
40 while (bb2.remaining() > 0)
41 bb2.putInt(bb1.getInt())
42 val time = System.nanoTime() - start
43 val operations = bb1.capacity() / Integer.BYTES
44 return time.toDouble() / operations
47 fun measureAverageCopyTimeInNanos(bb1: ByteBuffer, bb2: ByteBuffer): Double =
48 (0..NUMBER_OF_ITERATIONS).map { measureCopyTimeInNanos(bb1, bb2) }.average()
50 fun measureAndPrintAverageCopyTime(message: String, bb1: ByteBuffer, bb2: ByteBuffer) {
51 val avg = measureAverageCopyTimeInNanos(bb1, bb2)
52 System.out.printf("Each putInt+getInt for %s took an average of %.1f ns%n", message, avg)
55 for (singleBufferSize in BUFFER_SIZES) {
57 xdescribe("$singleBufferSize bytes buffers") {
58 describe("direct buffers") {
60 val bb1 = ByteBuffer.allocateDirect(singleBufferSize)
61 val bb2 = ByteBuffer.allocateDirect(singleBufferSize)
63 it("should be heated up") {
64 measureAverageCopyTimeInNanos(bb1, bb2)
67 it("should work fast") {
68 measureAndPrintAverageCopyTime("direct buffers of $singleBufferSize bytes", bb1, bb2)
72 describe("on-heap buffers") {
74 val bb1 = ByteBuffer.allocate(singleBufferSize)
75 val bb2 = ByteBuffer.allocate(singleBufferSize)
77 it("should be heated up") {
78 measureAverageCopyTimeInNanos(bb1, bb2)
81 it("should work fast") {
82 measureAndPrintAverageCopyTime("onheap buffers of $singleBufferSize bytes", bb1, bb2)