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.
 
 
 
 

87 lines
2.4 KiB

  1. using BenchmarkDotNet.Attributes;
  2. using MQTTnet.Adapter;
  3. using MQTTnet.Core.Internal;
  4. using MQTTnet.Diagnostics;
  5. using MQTTnet.Internal;
  6. using MQTTnet.Packets;
  7. using MQTTnet.Serializer;
  8. using System;
  9. using System.IO;
  10. using System.Threading;
  11. namespace MQTTnet.Benchmarks
  12. {
  13. [MemoryDiagnoser]
  14. public class ChannelAdapterBenchmark
  15. {
  16. private MqttChannelAdapter _channelAdapter;
  17. private int _iterations;
  18. private MemoryStream _stream;
  19. private MqttPublishPacket _packet;
  20. [GlobalSetup]
  21. public void Setup()
  22. {
  23. var message = new MqttApplicationMessageBuilder()
  24. .WithTopic("A")
  25. .Build();
  26. _packet = message.ToPublishPacket();
  27. var serializer = new MqttPacketSerializer();
  28. var serializedPacket = Join(serializer.Serialize(_packet));
  29. _iterations = 10000;
  30. _stream = new MemoryStream(_iterations * serializedPacket.Length);
  31. for (var i = 0; i < _iterations; i++)
  32. {
  33. _stream.Write(serializedPacket, 0, serializedPacket.Length);
  34. }
  35. _stream.Position = 0;
  36. var channel = new TestMqttChannel(_stream);
  37. _channelAdapter = new MqttChannelAdapter(channel, serializer, new MqttNetLogger().CreateChildLogger(nameof(MqttChannelAdapter)));
  38. }
  39. [Benchmark]
  40. public void Receive_10000_Messages()
  41. {
  42. _stream.Position = 0;
  43. for (var i = 0; i < 10000; i++)
  44. {
  45. _channelAdapter.ReceivePacketAsync(TimeSpan.Zero, CancellationToken.None).GetAwaiter().GetResult();
  46. }
  47. _stream.Position = 0;
  48. }
  49. [Benchmark]
  50. public void Send_10000_Messages()
  51. {
  52. _stream.Position = 0;
  53. for (var i = 0; i < 10000; i++)
  54. {
  55. _channelAdapter.SendPacketsAsync(TimeSpan.FromSeconds(15), new[] { _packet }, CancellationToken.None).GetAwaiter().GetResult();
  56. }
  57. _stream.Position = 0;
  58. }
  59. private static byte[] Join(params ArraySegment<byte>[] chunks)
  60. {
  61. var buffer = new MemoryStream();
  62. foreach (var chunk in chunks)
  63. {
  64. buffer.Write(chunk.Array, chunk.Offset, chunk.Count);
  65. }
  66. return buffer.ToArray();
  67. }
  68. }
  69. }