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.
 
 
 
 

112 regels
3.1 KiB

  1. using BenchmarkDotNet.Attributes;
  2. using MQTTnet.Packets;
  3. using System;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using MQTTnet.Adapter;
  7. using MQTTnet.Channel;
  8. using MQTTnet.Formatter;
  9. using MQTTnet.Formatter.V3;
  10. namespace MQTTnet.Benchmarks
  11. {
  12. [ClrJob]
  13. [RPlotExporter]
  14. [MemoryDiagnoser]
  15. public class SerializerBenchmark
  16. {
  17. private MqttBasePacket _packet;
  18. private ArraySegment<byte> _serializedPacket;
  19. private IMqttPacketFormatter _serializer;
  20. [GlobalSetup]
  21. public void Setup()
  22. {
  23. _packet = new MqttPublishPacket
  24. {
  25. Topic = "A"
  26. };
  27. _serializer = new MqttV311PacketFormatter();
  28. _serializedPacket = _serializer.Encode(_packet);
  29. }
  30. [Benchmark]
  31. public void Serialize_10000_Messages()
  32. {
  33. for (var i = 0; i < 10000; i++)
  34. {
  35. _serializer.Encode(_packet);
  36. _serializer.FreeBuffer();
  37. }
  38. }
  39. [Benchmark]
  40. public void Deserialize_10000_Messages()
  41. {
  42. var channel = new BenchmarkMqttChannel(_serializedPacket);
  43. var fixedHeader = new byte[2];
  44. var reader = new MqttPacketReader(channel);
  45. for (var i = 0; i < 10000; i++)
  46. {
  47. channel.Reset();
  48. var header = reader.ReadFixedHeaderAsync(fixedHeader, CancellationToken.None).GetAwaiter().GetResult();
  49. var receivedPacket = new ReceivedMqttPacket(
  50. header.Flags,
  51. new MqttPacketBodyReader(_serializedPacket.Array, (ulong)(_serializedPacket.Count - header.RemainingLength), (ulong)_serializedPacket.Array.Length), 0);
  52. _serializer.Decode(receivedPacket);
  53. }
  54. }
  55. private class BenchmarkMqttChannel : IMqttChannel
  56. {
  57. private readonly ArraySegment<byte> _buffer;
  58. private int _position;
  59. public BenchmarkMqttChannel(ArraySegment<byte> buffer)
  60. {
  61. _buffer = buffer;
  62. _position = _buffer.Offset;
  63. }
  64. public string Endpoint { get; }
  65. public void Reset()
  66. {
  67. _position = _buffer.Offset;
  68. }
  69. public Task ConnectAsync(CancellationToken cancellationToken)
  70. {
  71. throw new NotImplementedException();
  72. }
  73. public Task DisconnectAsync()
  74. {
  75. throw new NotImplementedException();
  76. }
  77. public Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  78. {
  79. Array.Copy(_buffer.Array, _position, buffer, offset, count);
  80. _position += count;
  81. return Task.FromResult(count);
  82. }
  83. public Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  84. {
  85. throw new NotImplementedException();
  86. }
  87. public void Dispose()
  88. {
  89. }
  90. }
  91. }
  92. }