websocket_frame_perftest.cc 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2014 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "net/websockets/websocket_frame.h"
  5. #include <algorithm>
  6. #include <vector>
  7. #include "base/timer/elapsed_timer.h"
  8. #include "testing/gtest/include/gtest/gtest.h"
  9. #include "testing/perf/perf_result_reporter.h"
  10. namespace net {
  11. namespace {
  12. const int kIterations = 100000;
  13. const int kLongPayloadSize = 1 << 16;
  14. const char kMaskingKey[] = "\xFE\xED\xBE\xEF";
  15. static constexpr char kMetricPrefixWebSocketFrame[] = "WebSocketFrameMask.";
  16. static constexpr char kMetricMaskTimeMs[] = "mask_time";
  17. perf_test::PerfResultReporter SetUpWebSocketFrameMaskReporter(
  18. const std::string& story) {
  19. perf_test::PerfResultReporter reporter(kMetricPrefixWebSocketFrame, story);
  20. reporter.RegisterImportantMetric(kMetricMaskTimeMs, "ms");
  21. return reporter;
  22. }
  23. static_assert(std::size(kMaskingKey) ==
  24. WebSocketFrameHeader::kMaskingKeyLength + 1,
  25. "incorrect masking key size");
  26. class WebSocketFrameTestMaskBenchmark : public ::testing::Test {
  27. protected:
  28. void Benchmark(const char* const story,
  29. const char* const payload,
  30. size_t size) {
  31. std::vector<char> scratch(payload, payload + size);
  32. WebSocketMaskingKey masking_key;
  33. std::copy(kMaskingKey,
  34. kMaskingKey + WebSocketFrameHeader::kMaskingKeyLength,
  35. masking_key.key);
  36. auto reporter = SetUpWebSocketFrameMaskReporter(story);
  37. base::ElapsedTimer timer;
  38. for (int x = 0; x < kIterations; ++x) {
  39. MaskWebSocketFramePayload(masking_key, x % size, scratch.data(),
  40. scratch.size());
  41. }
  42. reporter.AddResult(kMetricMaskTimeMs, timer.Elapsed().InMillisecondsF());
  43. }
  44. };
  45. TEST_F(WebSocketFrameTestMaskBenchmark, BenchmarkMaskShortPayload) {
  46. static const char kShortPayload[] = "Short Payload";
  47. Benchmark("short_payload", kShortPayload, std::size(kShortPayload));
  48. }
  49. TEST_F(WebSocketFrameTestMaskBenchmark, BenchmarkMaskLongPayload) {
  50. std::vector<char> payload(kLongPayloadSize, 'a');
  51. Benchmark("long_payload", payload.data(), payload.size());
  52. }
  53. // A 31-byte payload is guaranteed to do 7 byte mask operations and 3 vector
  54. // mask operations with an 8-byte vector. With a 16-byte vector it will fall
  55. // back to the byte-only code path and do 31 byte mask operations.
  56. TEST_F(WebSocketFrameTestMaskBenchmark, Benchmark31BytePayload) {
  57. std::vector<char> payload(31, 'a');
  58. Benchmark("31_payload", payload.data(), payload.size());
  59. }
  60. } // namespace
  61. } // namespace net