ProtoBench.java 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2009 Google Inc. All rights reserved.
  3. // http://code.google.com/p/protobuf/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. package com.google.protocolbuffers;
  31. import java.io.ByteArrayInputStream;
  32. import java.io.ByteArrayOutputStream;
  33. import java.io.File;
  34. import java.io.IOException;
  35. import java.io.RandomAccessFile;
  36. import java.lang.reflect.Method;
  37. import com.google.protobuf.ByteString;
  38. import com.google.protobuf.CodedInputStream;
  39. import com.google.protobuf.Message;
  40. public class ProtoBench {
  41. private static final long MIN_SAMPLE_TIME_MS = 2 * 1000;
  42. private static final long TARGET_TIME_MS = 30 * 1000;
  43. private ProtoBench() {
  44. // Prevent instantiation
  45. }
  46. public static void main(String[] args) {
  47. if (args.length < 2 || (args.length % 2) != 0) {
  48. System.err.println("Usage: ProtoBench <descriptor type name> <input data>");
  49. System.err.println("The descriptor type name is the fully-qualified message name,");
  50. System.err.println("e.g. com.google.protocolbuffers.benchmark.Message1");
  51. System.err.println("(You can specify multiple pairs of descriptor type name and input data.)");
  52. System.exit(1);
  53. }
  54. boolean success = true;
  55. for (int i = 0; i < args.length; i += 2) {
  56. success &= runTest(args[i], args[i + 1]);
  57. }
  58. System.exit(success ? 0 : 1);
  59. }
  60. /**
  61. * Runs a single test. Error messages are displayed to stderr, and the return value
  62. * indicates general success/failure.
  63. */
  64. public static boolean runTest(String type, String file) {
  65. System.out.println("Benchmarking " + type + " with file " + file);
  66. final Message defaultMessage;
  67. try {
  68. Class<?> clazz = Class.forName(type);
  69. Method method = clazz.getDeclaredMethod("getDefaultInstance");
  70. defaultMessage = (Message) method.invoke(null);
  71. } catch (Exception e) {
  72. // We want to do the same thing with all exceptions. Not generally nice,
  73. // but this is slightly different.
  74. System.err.println("Unable to get default message for " + type);
  75. return false;
  76. }
  77. try {
  78. final byte[] inputData = readAllBytes(file);
  79. final ByteArrayInputStream inputStream = new ByteArrayInputStream(inputData);
  80. final ByteString inputString = ByteString.copyFrom(inputData);
  81. final Message sampleMessage = defaultMessage.newBuilderForType().mergeFrom(inputString).build();
  82. benchmark("Serialize to byte string", inputData.length, new Action() {
  83. public void execute() { sampleMessage.toByteString(); }
  84. });
  85. benchmark("Serialize to byte array", inputData.length, new Action() {
  86. public void execute() { sampleMessage.toByteArray(); }
  87. });
  88. benchmark("Serialize to memory stream", inputData.length, new Action() {
  89. public void execute() throws IOException {
  90. sampleMessage.writeTo(new ByteArrayOutputStream());
  91. }
  92. });
  93. benchmark("Deserialize from byte string", inputData.length, new Action() {
  94. public void execute() throws IOException {
  95. defaultMessage.newBuilderForType().mergeFrom(inputString).build();
  96. }
  97. });
  98. benchmark("Deserialize from byte array", inputData.length, new Action() {
  99. public void execute() throws IOException {
  100. defaultMessage.newBuilderForType()
  101. .mergeFrom(CodedInputStream.newInstance(inputData)).build();
  102. }
  103. });
  104. benchmark("Deserialize from memory stream", inputData.length, new Action() {
  105. public void execute() throws IOException {
  106. defaultMessage.newBuilderForType()
  107. .mergeFrom(CodedInputStream.newInstance(inputStream)).build();
  108. inputStream.reset();
  109. }
  110. });
  111. System.out.println();
  112. return true;
  113. } catch (Exception e) {
  114. System.err.println("Error: " + e.getMessage());
  115. System.err.println("Detailed exception information:");
  116. e.printStackTrace(System.err);
  117. return false;
  118. }
  119. }
  120. private static void benchmark(String name, long dataSize, Action action) throws IOException {
  121. // Make sure it's JITted "reasonably" hard before running the first progress test
  122. for (int i=0; i < 100; i++) {
  123. action.execute();
  124. }
  125. // Run it progressively more times until we've got a reasonable sample
  126. int iterations = 1;
  127. long elapsed = timeAction(action, iterations);
  128. while (elapsed < MIN_SAMPLE_TIME_MS) {
  129. iterations *= 2;
  130. elapsed = timeAction(action, iterations);
  131. }
  132. // Upscale the sample to the target time. Do this in floating point arithmetic
  133. // to avoid overflow issues.
  134. iterations = (int) ((TARGET_TIME_MS / (double) elapsed) * iterations);
  135. elapsed = timeAction(action, iterations);
  136. System.out.println(name + ": " + iterations + " iterations in "
  137. + (elapsed/1000f) + "s; "
  138. + (iterations * dataSize) / (elapsed * 1024 * 1024 / 1000f)
  139. + "MB/s");
  140. }
  141. private static long timeAction(Action action, int iterations) throws IOException {
  142. System.gc();
  143. long start = System.currentTimeMillis();
  144. for (int i = 0; i < iterations; i++) {
  145. action.execute();
  146. }
  147. long end = System.currentTimeMillis();
  148. return end - start;
  149. }
  150. private static byte[] readAllBytes(String filename) throws IOException {
  151. RandomAccessFile file = new RandomAccessFile(new File(filename), "r");
  152. byte[] content = new byte[(int) file.length()];
  153. file.readFully(content);
  154. return content;
  155. }
  156. /**
  157. * Interface used to capture a single action to benchmark.
  158. */
  159. interface Action {
  160. void execute() throws IOException;
  161. }
  162. }