|
| 1 | +package com.stringcompressor; |
| 2 | + |
| 3 | +import org.openjdk.jmh.annotations.Benchmark; |
| 4 | +import org.openjdk.jmh.runner.Runner; |
| 5 | +import org.openjdk.jmh.runner.RunnerException; |
| 6 | +import org.openjdk.jmh.runner.options.OptionsBuilder; |
| 7 | + |
| 8 | +import java.util.Random; |
| 9 | + |
| 10 | +import static com.stringcompressor.FourBitAsciiCompressor.DEFAULT_4BIT_CHARSET; |
| 11 | + |
| 12 | +/** |
| 13 | + * @author Jean Dannemann Carone |
| 14 | + */ |
| 15 | +public class FourBitAsciiCompressorBenchmark { |
| 16 | + |
| 17 | + private static final AsciiCompressor COMPRESSOR = new FourBitAsciiCompressor(true); |
| 18 | + private static final int MAX_STRINGS = 128; // Must be a power of 2 for bitwise module. |
| 19 | + private static final byte[][] INPUT_STRINGS = new byte[MAX_STRINGS][]; |
| 20 | + private static final byte[][] COMPRESSED_STRINGS = new byte[MAX_STRINGS][]; |
| 21 | + private static final Random RANDOM = new Random(); |
| 22 | + |
| 23 | + private static int index; |
| 24 | + |
| 25 | + static { |
| 26 | + System.out.println(" ### Initializing static data for FourBitAsciiCompressorBenchmark..."); |
| 27 | + |
| 28 | + int charSetLen = DEFAULT_4BIT_CHARSET.length; |
| 29 | + |
| 30 | + for (int i = 0; i < MAX_STRINGS; i++) { |
| 31 | + byte[] string = new byte[10 * 1024 * 1024]; // 10 MB string. |
| 32 | + |
| 33 | + for (int j = 0, len = string.length; j < len; j++) |
| 34 | + string[j] = DEFAULT_4BIT_CHARSET[RANDOM.nextInt(charSetLen)]; |
| 35 | + |
| 36 | + INPUT_STRINGS[i] = string; |
| 37 | + COMPRESSED_STRINGS[i] = COMPRESSOR.compress(string); |
| 38 | + } |
| 39 | + |
| 40 | + System.out.println(" ### FourBitAsciiCompressorBenchmark static data initialized."); |
| 41 | + } |
| 42 | + |
| 43 | +// @Benchmark |
| 44 | +// public void baseline() { |
| 45 | +// } |
| 46 | + |
| 47 | + @Benchmark |
| 48 | + public byte[] compressStrings() { |
| 49 | + return COMPRESSOR.compress(INPUT_STRINGS[index++ & 0x7FFFFFFF & MAX_STRINGS - 1]); |
| 50 | + } |
| 51 | + |
| 52 | + @Benchmark |
| 53 | + public byte[] decompressStrings() { |
| 54 | + return COMPRESSOR.decompress(COMPRESSED_STRINGS[index++ & 0x7FFFFFFF & MAX_STRINGS - 1]); |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * For debugging (see JMH in build.gradle.kts). |
| 59 | + */ |
| 60 | + public static void main(String[] args) throws RunnerException { |
| 61 | + new Runner( |
| 62 | + new OptionsBuilder() |
| 63 | + .include(FourBitAsciiCompressorBenchmark.class.getSimpleName()) |
| 64 | + .forks(0) |
| 65 | + .build()) |
| 66 | + .run(); |
| 67 | + } |
| 68 | + |
| 69 | +} |
0 commit comments