ProtoBench.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2009 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  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 com.google.protobuf.ByteString;
  32. import com.google.protobuf.CodedInputStream;
  33. import com.google.protobuf.CodedOutputStream;
  34. import com.google.protobuf.ExtensionRegistry;
  35. import com.google.protobuf.Message;
  36. import com.google.protobuf.benchmarks.Benchmarks.BenchmarkDataset;
  37. import java.io.ByteArrayInputStream;
  38. import java.io.ByteArrayOutputStream;
  39. import java.io.File;
  40. import java.io.FileNotFoundException;
  41. import java.io.FileOutputStream;
  42. import java.io.IOException;
  43. import java.io.RandomAccessFile;
  44. import java.util.ArrayList;
  45. import java.util.List;
  46. public class ProtoBench {
  47. private static final long MIN_SAMPLE_TIME_MS = 1 * 1000;
  48. private static final long TARGET_TIME_MS = 5 * 1000;
  49. private ProtoBench() {
  50. // Prevent instantiation
  51. }
  52. public static void main(String[] args) {
  53. if (args.length < 1) {
  54. System.err.println("Usage: ./java-benchmark <input data>");
  55. System.err.println("input data is in the format of \"benchmarks.proto\"");
  56. System.exit(1);
  57. }
  58. boolean success = true;
  59. for (int i = 0; i < args.length; i++) {
  60. success &= runTest(args[i]);
  61. }
  62. System.exit(success ? 0 : 1);
  63. }
  64. public static ExtensionRegistry getExtensionsRegistry(BenchmarkDataset benchmarkDataset) {
  65. ExtensionRegistry extensions = ExtensionRegistry.newInstance();
  66. if (benchmarkDataset.getMessageName().equals("benchmarks.google_message3.GoogleMessage3")) {
  67. benchmarks.google_message3.BenchmarkMessage38.registerAllExtensions(extensions);
  68. benchmarks.google_message3.BenchmarkMessage37.registerAllExtensions(extensions);
  69. benchmarks.google_message3.BenchmarkMessage36.registerAllExtensions(extensions);
  70. benchmarks.google_message3.BenchmarkMessage35.registerAllExtensions(extensions);
  71. benchmarks.google_message3.BenchmarkMessage34.registerAllExtensions(extensions);
  72. benchmarks.google_message3.BenchmarkMessage33.registerAllExtensions(extensions);
  73. benchmarks.google_message3.BenchmarkMessage32.registerAllExtensions(extensions);
  74. benchmarks.google_message3.BenchmarkMessage31.registerAllExtensions(extensions);
  75. benchmarks.google_message3.BenchmarkMessage3.registerAllExtensions(extensions);
  76. } else if (benchmarkDataset.getMessageName().equals(
  77. "benchmarks.google_message4.GoogleMessage4")) {
  78. benchmarks.google_message4.BenchmarkMessage43.registerAllExtensions(extensions);
  79. benchmarks.google_message4.BenchmarkMessage42.registerAllExtensions(extensions);
  80. benchmarks.google_message4.BenchmarkMessage41.registerAllExtensions(extensions);
  81. benchmarks.google_message4.BenchmarkMessage4.registerAllExtensions(extensions);
  82. }
  83. return extensions;
  84. }
  85. /**
  86. * Return an message instance for one specific dataset, and register the extensions for that
  87. * message.
  88. */
  89. public static Message registerBenchmarks(BenchmarkDataset benchmarkDataset) {
  90. if (benchmarkDataset.getMessageName().equals("benchmarks.proto3.GoogleMessage1")) {
  91. return com.google.protobuf.benchmarks.BenchmarkMessage1Proto3.GoogleMessage1
  92. .getDefaultInstance();
  93. } else if (benchmarkDataset.getMessageName().equals("benchmarks.proto2.GoogleMessage1")) {
  94. return com.google.protobuf.benchmarks.BenchmarkMessage1Proto2.GoogleMessage1
  95. .getDefaultInstance();
  96. } else if (benchmarkDataset.getMessageName().equals("benchmarks.proto2.GoogleMessage2")) {
  97. return com.google.protobuf.benchmarks.BenchmarkMessage2.GoogleMessage2.getDefaultInstance();
  98. } else if (benchmarkDataset.getMessageName().
  99. equals("benchmarks.google_message3.GoogleMessage3")) {
  100. return benchmarks.google_message3.BenchmarkMessage3.GoogleMessage3.getDefaultInstance();
  101. } else if (benchmarkDataset.getMessageName().
  102. equals("benchmarks.google_message4.GoogleMessage4")) {
  103. return benchmarks.google_message4.BenchmarkMessage4.GoogleMessage4.getDefaultInstance();
  104. } else {
  105. return null;
  106. }
  107. }
  108. /**
  109. * Runs a single test. Error messages are displayed to stderr, and the return value indicates
  110. * general success/failure.
  111. */
  112. public static boolean runTest(String file) {
  113. final Message defaultMessage;
  114. BenchmarkDataset benchmarkDataset;
  115. ExtensionRegistry extensions;
  116. final byte[] inputData;
  117. try {
  118. inputData = readAllBytes(file);
  119. benchmarkDataset = BenchmarkDataset.parseFrom(inputData);
  120. } catch (IOException e) {
  121. System.err.println("Unable to get input data");
  122. return false;
  123. }
  124. defaultMessage = registerBenchmarks(benchmarkDataset);
  125. extensions = getExtensionsRegistry(benchmarkDataset);
  126. if (defaultMessage == null) {
  127. System.err.println("Unable to get default message " + benchmarkDataset.getMessageName());
  128. return false;
  129. }
  130. System.out.println("Benchmarking " + benchmarkDataset.getMessageName() + " with file " + file);
  131. try {
  132. List<byte[]> inputDataList = new ArrayList<byte[]>();
  133. List<ByteArrayInputStream> inputStreamList = new ArrayList<ByteArrayInputStream>();
  134. List<ByteString> inputStringList = new ArrayList<ByteString>();
  135. List<Message> sampleMessageList = new ArrayList<Message>();
  136. for (int i = 0; i < benchmarkDataset.getPayloadCount(); i++) {
  137. byte[] singleInputData = benchmarkDataset.getPayload(i).toByteArray();
  138. inputDataList.add(benchmarkDataset.getPayload(i).toByteArray());
  139. inputStreamList.add(new ByteArrayInputStream(benchmarkDataset.getPayload(i).toByteArray()));
  140. inputStringList.add(benchmarkDataset.getPayload(i));
  141. sampleMessageList.add(
  142. defaultMessage.newBuilderForType().mergeFrom(singleInputData, extensions).build());
  143. }
  144. FileOutputStream devNullTemp = null;
  145. CodedOutputStream reuseDevNullTemp = null;
  146. try {
  147. devNullTemp = new FileOutputStream("/dev/null");
  148. reuseDevNullTemp = CodedOutputStream.newInstance(devNullTemp);
  149. } catch (FileNotFoundException e) {
  150. // ignore: this is probably Windows, where /dev/null does not exist
  151. }
  152. final FileOutputStream devNull = devNullTemp;
  153. final CodedOutputStream reuseDevNull = reuseDevNullTemp;
  154. benchmark(
  155. "Serialize to byte string",
  156. inputData.length,
  157. new Action() {
  158. public void execute() {
  159. for (int i = 0; i < sampleMessageList.size(); i++) {
  160. sampleMessageList.get(i).toByteString();
  161. }
  162. }
  163. });
  164. benchmark(
  165. "Serialize to byte array",
  166. inputData.length,
  167. new Action() {
  168. public void execute() {
  169. for (int i = 0; i < sampleMessageList.size(); i++) {
  170. sampleMessageList.get(i).toByteString();
  171. }
  172. }
  173. });
  174. benchmark(
  175. "Serialize to memory stream",
  176. inputData.length,
  177. new Action() {
  178. public void execute() throws IOException {
  179. ByteArrayOutputStream output = new ByteArrayOutputStream();
  180. for (int i = 0; i < sampleMessageList.size(); i++) {
  181. sampleMessageList.get(i).writeTo(output);
  182. }
  183. }
  184. });
  185. if (devNull != null) {
  186. benchmark(
  187. "Serialize to /dev/null with FileOutputStream",
  188. inputData.length,
  189. new Action() {
  190. public void execute() throws IOException {
  191. for (int i = 0; i < sampleMessageList.size(); i++) {
  192. sampleMessageList.get(i).writeTo(devNull);
  193. }
  194. }
  195. });
  196. benchmark(
  197. "Serialize to /dev/null reusing FileOutputStream",
  198. inputData.length,
  199. new Action() {
  200. public void execute() throws IOException {
  201. for (int i = 0; i < sampleMessageList.size(); i++) {
  202. sampleMessageList.get(i).writeTo(reuseDevNull);
  203. reuseDevNull.flush(); // force the write to the OutputStream
  204. }
  205. }
  206. });
  207. }
  208. benchmark(
  209. "Deserialize from byte string",
  210. inputData.length,
  211. new Action() {
  212. public void execute() throws IOException {
  213. for (int i = 0; i < inputStringList.size(); i++) {
  214. defaultMessage
  215. .newBuilderForType()
  216. .mergeFrom(inputStringList.get(i), extensions)
  217. .build();
  218. }
  219. }
  220. });
  221. benchmark(
  222. "Deserialize from byte array",
  223. inputData.length,
  224. new Action() {
  225. public void execute() throws IOException {
  226. for (int i = 0; i < inputDataList.size(); i++) {
  227. defaultMessage
  228. .newBuilderForType()
  229. .mergeFrom(CodedInputStream.newInstance(inputDataList.get(i)), extensions)
  230. .build();
  231. }
  232. }
  233. });
  234. benchmark(
  235. "Deserialize from memory stream",
  236. inputData.length,
  237. new Action() {
  238. public void execute() throws IOException {
  239. for (int i = 0; i < inputStreamList.size(); i++) {
  240. defaultMessage
  241. .newBuilderForType()
  242. .mergeFrom(CodedInputStream.newInstance(inputStreamList.get(i)), extensions)
  243. .build();
  244. inputStreamList.get(i).reset();
  245. }
  246. }
  247. });
  248. System.out.println();
  249. return true;
  250. } catch (Exception e) {
  251. System.err.println("Error: " + e.getMessage());
  252. System.err.println("Detailed exception information:");
  253. e.printStackTrace(System.err);
  254. return false;
  255. }
  256. }
  257. private static void benchmark(String name, long dataSize, Action action) throws IOException {
  258. // Make sure it's JITted "reasonably" hard before running the first progress test
  259. for (int i=0; i < 100; i++) {
  260. action.execute();
  261. }
  262. // Run it progressively more times until we've got a reasonable sample
  263. int iterations = 1;
  264. long elapsed = timeAction(action, iterations);
  265. while (elapsed < MIN_SAMPLE_TIME_MS) {
  266. iterations *= 2;
  267. elapsed = timeAction(action, iterations);
  268. }
  269. // Upscale the sample to the target time. Do this in floating point arithmetic
  270. // to avoid overflow issues.
  271. iterations = (int) ((TARGET_TIME_MS / (double) elapsed) * iterations);
  272. elapsed = timeAction(action, iterations);
  273. System.out.println(name + ": " + iterations + " iterations in "
  274. + (elapsed/1000f) + "s; "
  275. + (iterations * dataSize) / (elapsed * 1024 * 1024 / 1000f)
  276. + "MB/s");
  277. }
  278. private static long timeAction(Action action, int iterations) throws IOException {
  279. System.gc();
  280. long start = System.currentTimeMillis();
  281. for (int i = 0; i < iterations; i++) {
  282. action.execute();
  283. }
  284. long end = System.currentTimeMillis();
  285. return end - start;
  286. }
  287. private static byte[] readAllBytes(String filename) throws IOException {
  288. RandomAccessFile file = new RandomAccessFile(new File(filename), "r");
  289. byte[] content = new byte[(int) file.length()];
  290. file.readFully(content);
  291. return content;
  292. }
  293. /**
  294. * Interface used to capture a single action to benchmark.
  295. */
  296. interface Action {
  297. void execute() throws IOException;
  298. }
  299. }