blob: 78557e050454ef22e3fb4178819b210ecd866122 [file] [log] [blame]
Narayan Kamathfa07c882016-02-12 12:54:37 +00001/*
2 * Copyright (C) 2016 The Android Open Source Project
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 benchmarks;
18
19import com.google.caliper.BeforeExperiment;
20import com.google.caliper.Param;
21import java.io.File;
22import java.io.FileOutputStream;
23import java.io.IOException;
24import java.util.Enumeration;
25import java.util.Random;
26import java.util.zip.ZipEntry;
27import java.util.zip.ZipFile;
28import java.util.zip.ZipOutputStream;
29
30
31public class ZipFileBenchmark {
32
33 private File file;
34 @Param({"128", "1024", "8192"}) int numEntries;
35
36 @BeforeExperiment
37 protected void setUp() throws Exception {
38 System.setProperty("java.io.tmpdir", "/data/local/tmp");
39 file = File.createTempFile(getClass().getName(), ".zip");
40 file.deleteOnExit();
41 writeEntries(new ZipOutputStream(new FileOutputStream(file)), numEntries, 0);
42 ZipFile zipFile = new ZipFile(file);
43 for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements(); ) {
44 ZipEntry zipEntry = e.nextElement();
45 }
46 zipFile.close();
47 }
48
49 public void timeZipFileOpen(int reps) throws Exception {
50 for (int i = 0; i < reps; ++i) {
51 ZipFile zf = new ZipFile(file);
52 }
53 }
54
55 /**
56 * Compresses the given number of files, each of the given size, into a .zip archive.
57 */
58 protected void writeEntries(ZipOutputStream out, int entryCount, long entrySize)
59 throws IOException {
60 byte[] writeBuffer = new byte[8192];
61 Random random = new Random();
62 try {
63 for (int entry = 0; entry < entryCount; ++entry) {
64 ZipEntry ze = new ZipEntry(Integer.toHexString(entry));
65 ze.setSize(entrySize);
66 out.putNextEntry(ze);
67
68 for (long i = 0; i < entrySize; i += writeBuffer.length) {
69 random.nextBytes(writeBuffer);
70 int byteCount = (int) Math.min(writeBuffer.length, entrySize - i);
71 out.write(writeBuffer, 0, byteCount);
72 }
73
74 out.closeEntry();
75 }
76 } finally {
77 out.close();
78 }
79 }
80}