Skip to content

Instantly share code, notes, and snippets.

@cgmb
Last active August 29, 2015 14:14
Show Gist options
  • Save cgmb/caa3527b7fdc148a4f57 to your computer and use it in GitHub Desktop.
Save cgmb/caa3527b7fdc148a4f57 to your computer and use it in GitHub Desktop.
A benchmark for how quickly random numbers can be written to file in Java
import java.util.Random;
import java.io.FileWriter;
import java.io.IOException;
class BenchmarkRandomNumberWriting {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Incorrect number of arguments!");
System.err.println(
"Usage: java BenchmarkRandomNumberGenerator <output file> <line count>");
System.exit(1);
}
// setup our file writer
FileWriter fw = null;
try {
fw = new FileWriter(args[0]);
} catch (IOException e) {
System.err.println("Failed to open " + args[0]);
System.err.println("Error: " + e.getMessage());
System.exit(2);
}
// check how many lines of output we should write
int count = 0;
try {
count = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
System.err.println(args[1] + " must be an integer");
System.exit(3);
}
// get the proper line-endings for the platform
// \n on Linux, \r\n on Windows
String lineSeperator = System.getProperty("line.separator");
// run our random number generator
Random rng = new Random();
long startTime = System.nanoTime();
try {
for (int i = 0; i < count; ++i) {
fw.write(Integer.toString(rng.nextInt()) + lineSeperator);
}
fw.close();
} catch (IOException e) {
System.err.println("Failed to write to " + args[0]);
System.err.println("Error: " + e.getMessage());
System.exit(2);
}
// print out how long it took
long endTime = System.nanoTime();
double elapsed = (endTime - startTime) / 1e9;
System.out.println(elapsed);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment