You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

91 lines
2.4 KiB

  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using BenchmarkDotNet.Attributes;
  5. using MQTTnet.Adapter;
  6. using MQTTnet.Internal;
  7. using MQTTnet.Packets;
  8. using System;
  9. using System.IO;
  10. using System.Threading;
  11. using MQTTnet.Diagnostics;
  12. using MQTTnet.Formatter;
  13. namespace MQTTnet.Benchmarks
  14. {
  15. [MemoryDiagnoser]
  16. public sealed class ChannelAdapterBenchmark
  17. {
  18. MqttChannelAdapter _channelAdapter;
  19. int _iterations;
  20. MemoryStream _stream;
  21. MqttPublishPacket _packet;
  22. [GlobalSetup]
  23. public void Setup()
  24. {
  25. _packet = new MqttPublishPacket
  26. {
  27. Topic = "A"
  28. };
  29. var serializer = new MqttPacketFormatterAdapter(MqttProtocolVersion.V311, new MqttBufferWriter(4096, 65535));
  30. var serializedPacket = Join(serializer.Encode(_packet).Join());
  31. _iterations = 10000;
  32. _stream = new MemoryStream(_iterations * serializedPacket.Length);
  33. for (var i = 0; i < _iterations; i++)
  34. {
  35. _stream.Write(serializedPacket, 0, serializedPacket.Length);
  36. }
  37. _stream.Position = 0;
  38. var channel = new TestMqttChannel(_stream);
  39. _channelAdapter = new MqttChannelAdapter(channel, serializer, null, new MqttNetEventLogger());
  40. }
  41. [Benchmark]
  42. public void Receive_10000_Messages()
  43. {
  44. _stream.Position = 0;
  45. for (var i = 0; i < 10000; i++)
  46. {
  47. _channelAdapter.ReceivePacketAsync(CancellationToken.None).GetAwaiter().GetResult();
  48. }
  49. _stream.Position = 0;
  50. }
  51. [Benchmark]
  52. public void Send_10000_Messages()
  53. {
  54. _stream.Position = 0;
  55. for (var i = 0; i < 10000; i++)
  56. {
  57. _channelAdapter.SendPacketAsync(_packet, CancellationToken.None).GetAwaiter().GetResult();
  58. }
  59. _stream.Position = 0;
  60. }
  61. static byte[] Join(params ArraySegment<byte>[] chunks)
  62. {
  63. var buffer = new MemoryStream();
  64. foreach (var chunk in chunks)
  65. {
  66. buffer.Write(chunk.Array, chunk.Offset, chunk.Count);
  67. }
  68. return buffer.ToArray();
  69. }
  70. }
  71. }