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.FileNotFoundException;
  27 import java.io.FileOutputStream;
  28 import java.io.IOException;
  29 import java.util.concurrent.TimeUnit;
  30 
  31 import org.openjdk.jmh.annotations.*;
  32 
  33 /**
  34  * Tests the overheads of I/O API.
  35  * This test is known to depend heavily on disk subsystem performance.
  36  */
  37 @BenchmarkMode(Mode.Throughput)
  38 @OutputTimeUnit(TimeUnit.MILLISECONDS)
  39 @State(Scope.Thread)
  40 public class FileWrite {
  41 
  42     @Param("1000000")
  43     private int fileSize;
  44 
  45     private File f;
  46     private FileOutputStream fos;
  47     private long count;
  48 
  49     @Setup(Level.Trial)
  50     public void beforeRun() throws IOException {
  51         f = File.createTempFile("FileWriteBench", ".bin");
  52     }
  53 
  54     @TearDown(Level.Trial)
  55     public void afterRun() throws IOException {
  56         f.delete();
  57     }
  58 
  59     @Setup(Level.Iteration)
  60     public void beforeIteration() throws FileNotFoundException {
  61         fos = new FileOutputStream(f);
  62     }
  63 
  64     @TearDown(Level.Iteration)
  65     public void afterIteration() throws IOException {
  66         fos.close();
  67     }
  68 
  69     @Benchmark
  70     public void test() throws IOException {
  71         fos.write((byte) count);
  72         count++;
  73         if (count >= fileSize) {
  74             // restart
  75             fos.close();
  76             fos = new FileOutputStream(f);
  77             count = 0;
  78         }
  79     }
  80 
  81 }