* Runs a single test. Error messages are displayed to stderr, and the return value
* indicates general success/failure.
*/
public static boolean runTest(String type, String file) {
System.out.println("Benchmarking " + type + " with file " + file);
final Message defaultMessage;
try {
Class<?> clazz = Class.forName(type);
Method method = clazz.getDeclaredMethod("getDefaultInstance");
defaultMessage = (Message) method.invoke(null);
} catch (Exception e) {
// We want to do the same thing with all exceptions. Not generally nice,
// but this is slightly different.
System.err.println("Unable to get default message for " + type);
return false;
}
try {
final byte[] inputData = readAllBytes(file);
final ByteArrayInputStream inputStream = new ByteArrayInputStream(inputData);
final ByteString inputString = ByteString.copyFrom(inputData);
final Message sampleMessage = defaultMessage.newBuilderForType().mergeFrom(inputString).build();
FileOutputStream devNullTemp = null;
CodedOutputStream reuseDevNullTemp = null;
try {
devNullTemp = new FileOutputStream("/dev/null");
reuseDevNullTemp = CodedOutputStream.newInstance(devNullTemp);
} catch (FileNotFoundException e) {
// ignore: this is probably Windows, where /dev/null does not exist
}
final FileOutputStream devNull = devNullTemp;
final CodedOutputStream reuseDevNull = reuseDevNullTemp;
benchmark("Serialize to byte string", inputData.length, new Action() {
public void execute() { sampleMessage.toByteString(); }
});
benchmark("Serialize to byte array", inputData.length, new Action() {
public void execute() { sampleMessage.toByteArray(); }
});
benchmark("Serialize to memory stream", inputData.length, new Action() {
public void execute() throws IOException {
sampleMessage.writeTo(new ByteArrayOutputStream());
}
});
if (devNull != null) {
benchmark("Serialize to /dev/null with FileOutputStream", inputData.length, new Action() {
public void execute() throws IOException {
sampleMessage.writeTo(devNull);
}
});
benchmark("Serialize to /dev/null reusing FileOutputStream", inputData.length, new Action() {
public void execute() throws IOException {
sampleMessage.writeTo(reuseDevNull);
reuseDevNull.flush(); // force the write to the OutputStream
}
});
}
benchmark("Deserialize from byte string", inputData.length, new Action() {