Skip to content

Instantly share code, notes, and snippets.

@taku0
Created March 29, 2015 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taku0/e68851bf357dda0f989c to your computer and use it in GitHub Desktop.
Save taku0/e68851bf357dda0f989c to your computer and use it in GitHub Desktop.
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