1 /*
   2  * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 package org.openjdk.bench.java.io;
  24 
  25 import java.io.File;
  26 import java.io.FileInputStream;
  27 import java.io.FileNotFoundException;
  28 import java.io.FileOutputStream;
  29 import java.io.IOException;
  30 import java.util.concurrent.TimeUnit;
  31 
  32 import org.openjdk.jmh.annotations.*;
  33 
  34 /**
  35  * Tests the overheads of I/O API.
  36  * This test is known to depend heavily on disk subsystem performance.
  37  */
  38 @BenchmarkMode(Mode.Throughput)
  39 @OutputTimeUnit(TimeUnit.MILLISECONDS)
  40 @State(Scope.Thread)
  41 public class FileRead {
  42 
  43     @Param("1000000")
  44     private int fileSize;
  45 
  46     private File f;
  47     private FileInputStream fis;
  48 
  49     @Setup(Level.Trial)
  50     public void beforeRun() throws IOException {
  51         f = File.createTempFile("FileReadBench", ".bin");
  52         try (FileOutputStream fos = new FileOutputStream(f)) {
  53             for (int i = 0; i < fileSize; i++) {
  54                 fos.write((byte) i);
  55             }
  56         }
  57     }
  58 
  59     @TearDown(Level.Trial)
  60     public void afterRun() throws IOException {
  61         f.delete();
  62     }
  63 
  64     @Setup(Level.Iteration)
  65     public void beforeIteration() throws FileNotFoundException {
  66         fis = new FileInputStream(f);
  67     }
  68 
  69     @TearDown(Level.Iteration)
  70     public void afterIteration() throws IOException {
  71         fis.close();
  72     }
  73 
  74     @Benchmark
  75     public void test() throws IOException {
  76         int ret = fis.read();
  77         if (ret == -1) {
  78             // start over
  79             fis.close();
  80             fis = new FileInputStream(f);
  81         }
  82     }
  83 
  84 }