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.
 
 
 
 

75 lines
2.2 KiB

  1. using BenchmarkDotNet.Attributes;
  2. using MQTTnet.Packets;
  3. using MQTTnet.Serializer;
  4. using MQTTnet.Internal;
  5. using BenchmarkDotNet.Attributes.Jobs;
  6. using BenchmarkDotNet.Attributes.Exporters;
  7. using System;
  8. using System.Threading;
  9. using System.IO;
  10. using MQTTnet.Adapter;
  11. namespace MQTTnet.Benchmarks
  12. {
  13. [ClrJob]
  14. [RPlotExporter]
  15. [MemoryDiagnoser]
  16. public class SerializerBenchmark
  17. {
  18. private MqttBasePacket _packet;
  19. private ArraySegment<byte> _serializedPacket;
  20. private MqttPacketSerializer _serializer;
  21. [GlobalSetup]
  22. public void Setup()
  23. {
  24. var message = new MqttApplicationMessageBuilder()
  25. .WithTopic("A")
  26. .Build();
  27. _packet = message.ToPublishPacket();
  28. _serializer = new MqttPacketSerializer();
  29. _serializedPacket = _serializer.Serialize(_packet);
  30. }
  31. [Benchmark]
  32. public void Serialize_10000_Messages()
  33. {
  34. for (var i = 0; i < 10000; i++)
  35. {
  36. _serializer.Serialize(_packet);
  37. }
  38. }
  39. [Benchmark]
  40. public void Deserialize_10000_Messages()
  41. {
  42. for (var i = 0; i < 10000; i++)
  43. {
  44. using (var headerStream = new MemoryStream(Join(_serializedPacket)))
  45. {
  46. var channel = new TestMqttChannel(headerStream);
  47. var header = MqttPacketReader.ReadFixedHeaderAsync(channel, CancellationToken.None).GetAwaiter().GetResult();
  48. using (var bodyStream = new MemoryStream(Join(_serializedPacket), (int)headerStream.Position, header.RemainingLength))
  49. {
  50. _serializer.Deserialize(new ReceivedMqttPacket(header.Flags, new MqttPacketBodyReader(bodyStream.ToArray())));
  51. }
  52. }
  53. }
  54. }
  55. private static byte[] Join(params ArraySegment<byte>[] chunks)
  56. {
  57. var buffer = new MemoryStream();
  58. foreach (var chunk in chunks)
  59. {
  60. buffer.Write(chunk.Array, chunk.Offset, chunk.Count);
  61. }
  62. return buffer.ToArray();
  63. }
  64. }
  65. }