1/*
2 * Copyright (C) 2010 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package examples;
18
19import com.google.caliper.Benchmark;
20import com.google.caliper.Param;
21import com.google.caliper.model.ArbitraryMeasurement;
22
23import java.io.ByteArrayOutputStream;
24import java.io.IOException;
25import java.util.HashMap;
26import java.util.Map;
27import java.util.zip.Deflater;
28
29/**
30 * Example "arbitrary measurement" benchmark.
31 */
32public class CompressionSizeBenchmark {
33
34  @Param({
35      "this string will compress badly",
36      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
37      "asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf"})
38  private String toCompress;
39  @Param({"bestCompression", "bestSpeed", "noCompression", "huffmanOnly"})
40  private String compressionLevel;
41
42  private double compressionRatio;
43
44  public static final Map<String, Integer> compressionLevelMap = new HashMap<String, Integer>();
45  static {
46      compressionLevelMap.put("bestCompression", Deflater.BEST_COMPRESSION);
47      compressionLevelMap.put("bestSpeed", Deflater.BEST_SPEED);
48      compressionLevelMap.put("noCompression", Deflater.NO_COMPRESSION);
49      compressionLevelMap.put("huffmanOnly", Deflater.HUFFMAN_ONLY);
50  }
51
52  @Benchmark long simpleCompression(int reps) {
53    long dummy = 0;
54    for (int i = 0; i < reps; i++) {
55      dummy += compress(toCompress.getBytes()).length;
56    }
57    return dummy;
58  }
59
60  @ArbitraryMeasurement(units = ":1", description = "ratio of uncompressed to compressed")
61  public double compressionSize() {
62    byte[] initialBytes = toCompress.getBytes();
63    byte[] finalBytes = compress(initialBytes);
64    compressionRatio = (double) initialBytes.length / (double) finalBytes.length;
65    return compressionRatio;
66  }
67
68  private byte[] compress(byte[] bytes) {
69    Deflater compressor = new Deflater();
70    compressor.setLevel(compressionLevelMap.get(compressionLevel));
71    compressor.setInput(bytes);
72    compressor.finish();
73    ByteArrayOutputStream bos = new ByteArrayOutputStream();
74    byte[] buf = new byte[1024];
75    while (!compressor.finished()) {
76      int count = compressor.deflate(buf);
77      bos.write(buf, 0, count);
78    }
79    try {
80      bos.close();
81    } catch (IOException e) {
82    }
83    return bos.toByteArray();
84  }
85}
86