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

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