Created
March 29, 2015 08:54
-
-
Save taku0/e68851bf357dda0f989c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
public class WriterBenchmark { | |
public static final int N = 1000000; | |
public static void main(String... args) throws IOException, InterruptedException { | |
long sum = 0; | |
for (int i = 0; i < 200; i++) { | |
long start = System.nanoTime(); | |
writeDirectly(); | |
// withBufferedWriter(); | |
// buffered(); | |
long time = System.nanoTime() - start; | |
System.out.println(i + " " + time / 1000.0 / 1000.0); | |
if (i >= 150) { | |
sum += time; | |
Thread.sleep(100); | |
} | |
} | |
System.out.println(sum / 50.0 / 1000.0 / 1000.0); | |
} | |
public static void writeDirectly() throws IOException { | |
Writer writer = new FileWriter("test.dat"); | |
try { | |
for (int i = 0; i < N; i++) { | |
writer.write("1"); | |
} | |
} finally { | |
writer.close(); | |
} | |
} | |
public static void withBufferedWriter() throws IOException { | |
Writer writer = new BufferedWriter(new FileWriter("test.dat")); | |
try { | |
for (int i = 0; i < N; i++) { | |
writer.write("1"); | |
} | |
} finally { | |
writer.close(); | |
} | |
} | |
public static void buffered() throws IOException { | |
StringBuilder builder = new StringBuilder(); | |
for (int i = 0; i < N; i++) { | |
builder.append("1"); | |
} | |
FileWriter writer = new FileWriter("test.dat"); | |
try { | |
writer.write(builder.toString()); | |
} finally { | |
writer.close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment