Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 

76 рядки
2.4 KiB

  1. using BenchmarkDotNet.Attributes;
  2. using MQTTnet.Channel;
  3. using MQTTnet.Client;
  4. using MQTTnet.Diagnostics;
  5. using MQTTnet.Implementations;
  6. using MQTTnet.Server;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  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.ClientAccepted += (sender, args) => _serverChannel = (IMqttChannel)args.Client.GetType().GetField("_channel", System.Reflection.BindingFlags.NonPublic| System.Reflection.BindingFlags.Instance).GetValue(args.Client);
  23. _mqttServer = factory.CreateMqttServer(new[] { tcpServer }, new MqttNetLogger());
  24. var serverOptions = new MqttServerOptionsBuilder().Build();
  25. _mqttServer.StartAsync(serverOptions).GetAwaiter().GetResult();
  26. var clientOptions = new MqttClientOptionsBuilder()
  27. .WithTcpServer("localhost").Build();
  28. var tcpOptions = (MqttClientTcpOptions) clientOptions.ChannelOptions;
  29. _clientChannel = new MqttTcpChannel(tcpOptions);
  30. _clientChannel.ConnectAsync(CancellationToken.None).GetAwaiter().GetResult();
  31. }
  32. [Benchmark]
  33. public async Task Send_10000_Chunks()
  34. {
  35. var size = 5;
  36. var iterations = 10000;
  37. await Task.WhenAll(WriteAsync(iterations, size), ReadAsync(iterations, size));
  38. }
  39. private async Task ReadAsync(int iterations, int size)
  40. {
  41. await Task.Yield();
  42. var expected = iterations * size;
  43. long read = 0;
  44. while (read < expected)
  45. {
  46. var readresult = await _clientChannel.ReadAsync(new byte[size], 0, size, CancellationToken.None).ConfigureAwait(false);
  47. read += readresult;
  48. }
  49. }
  50. private async Task WriteAsync(int iterations, int size)
  51. {
  52. await Task.Yield();
  53. for (var i = 0; i < iterations; i++)
  54. {
  55. await _serverChannel.WriteAsync(new byte[size], 0, size, CancellationToken.None).ConfigureAwait(false);
  56. }
  57. }
  58. }
  59. }