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.

MqttTcpChannelBenchmark.cs 2.6 KiB

6 jaren geleden
5 jaren geleden
6 jaren geleden
6 jaren geleden
6 jaren geleden
6 jaren geleden
6 jaren geleden
6 jaren geleden
6 jaren geleden
6 jaren geleden
6 jaren geleden
6 jaren geleden
6 jaren geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using BenchmarkDotNet.Attributes;
  2. using MQTTnet.Channel;
  3. using MQTTnet.Diagnostics;
  4. using MQTTnet.Implementations;
  5. using MQTTnet.Server;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MQTTnet.Client.Options;
  9. namespace MQTTnet.Benchmarks
  10. {
  11. [MemoryDiagnoser]
  12. public class MqttTcpChannelBenchmark
  13. {
  14. private IMqttServer _mqttServer;
  15. private IMqttChannel _serverChannel;
  16. private IMqttChannel _clientChannel;
  17. [GlobalSetup]
  18. public void Setup()
  19. {
  20. var factory = new MqttFactory();
  21. var tcpServer = new MqttTcpServerAdapter(new MqttNetLogger().CreateChildLogger());
  22. tcpServer.ClientHandler += args =>
  23. {
  24. _serverChannel =
  25. (IMqttChannel)args.GetType().GetField("_channel",
  26. System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
  27. .GetValue(args);
  28. return Task.CompletedTask;
  29. };
  30. _mqttServer = factory.CreateMqttServer(new[] { tcpServer }, new MqttNetLogger());
  31. var serverOptions = new MqttServerOptionsBuilder().Build();
  32. _mqttServer.StartAsync(serverOptions).GetAwaiter().GetResult();
  33. var clientOptions = new MqttClientOptionsBuilder()
  34. .WithTcpServer("localhost").Build();
  35. var tcpOptions = (MqttClientTcpOptions)clientOptions.ChannelOptions;
  36. _clientChannel = new MqttTcpChannel(new MqttClientOptions { ChannelOptions = tcpOptions });
  37. _clientChannel.ConnectAsync(CancellationToken.None).GetAwaiter().GetResult();
  38. }
  39. [Benchmark]
  40. public async Task Send_10000_Chunks()
  41. {
  42. var size = 5;
  43. var iterations = 10000;
  44. await Task.WhenAll(WriteAsync(iterations, size), ReadAsync(iterations, size));
  45. }
  46. private async Task ReadAsync(int iterations, int size)
  47. {
  48. await Task.Yield();
  49. var expected = iterations * size;
  50. long read = 0;
  51. while (read < expected)
  52. {
  53. var readresult = await _clientChannel.ReadAsync(new byte[size], 0, size, CancellationToken.None).ConfigureAwait(false);
  54. read += readresult;
  55. }
  56. }
  57. private async Task WriteAsync(int iterations, int size)
  58. {
  59. await Task.Yield();
  60. for (var i = 0; i < iterations; i++)
  61. {
  62. await _serverChannel.WriteAsync(new byte[size], 0, size, CancellationToken.None).ConfigureAwait(false);
  63. }
  64. }
  65. }
  66. }