您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

75 行
2.1 KiB

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