├── NetBenchmark
├── NetBenchmark
│ ├── ITester.cs
│ ├── TCPTester.cs
│ ├── NetBenchmark.csproj
│ ├── Counter.cs
│ ├── WebSocketTester.cs
│ ├── Benchmark.cs
│ ├── HttpTester.cs
│ ├── TimeStatistics.cs
│ └── Runner.cs
├── NetBenchmark.ConsoleTest
│ ├── NetBenchmark.ConsoleTest.csproj
│ └── Program.cs
└── NetBenchmark.sln
├── README.md
└── LICENSE
/NetBenchmark/NetBenchmark/ITester.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using System.Threading.Tasks;
5 |
6 | namespace NetBenchmark
7 | {
8 | public interface ITester
9 | {
10 | Runner Runner { get; set; }
11 |
12 | Task Execute();
13 |
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/NetBenchmark/NetBenchmark.ConsoleTest/NetBenchmark.ConsoleTest.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net5.0
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/NetBenchmark/NetBenchmark/TCPTester.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using System.Threading.Tasks;
5 |
6 | namespace NetBenchmark
7 | {
8 | public class TCPTester : ITester
9 | where Token : new()
10 | {
11 | public BeetleX.Clients.AwaiterClient Client { get; set; }
12 |
13 | public Runner Runner { get; set; }
14 |
15 | public Func Handler { get; set; }
16 |
17 | public Token Tag { get; set; } = new Token();
18 |
19 | public async Task Execute()
20 | {
21 | await Handler(Client, this.Tag);
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/NetBenchmark/NetBenchmark/NetBenchmark.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | henryfan
6 | beetlex-io.com
7 | Copyright © beetlex-io.com 2019-2022 email:henryfan@msn.com
8 | tcp http and websocket benchmark components
9 | https://github.com/IKende/NetBenchmark/blob/master/LICENSE
10 | https://github.com/beetlex-io/NetBenchmark
11 | 1.2
12 | BeetleX.NetBenchmark
13 |
14 | 1.2.0.0
15 | 1.2.0.0
16 | beetlex200.png
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 | True
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/NetBenchmark/NetBenchmark.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.28307.705
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetBenchmark", "NetBenchmark\NetBenchmark.csproj", "{B3B0D47D-0B5D-4BAC-B9DB-1D416960423F}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetBenchmark.ConsoleTest", "NetBenchmark.ConsoleTest\NetBenchmark.ConsoleTest.csproj", "{22615F90-D3FE-4FEB-B8F7-3009FF5825E4}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {B3B0D47D-0B5D-4BAC-B9DB-1D416960423F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {B3B0D47D-0B5D-4BAC-B9DB-1D416960423F}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {B3B0D47D-0B5D-4BAC-B9DB-1D416960423F}.Release|Any CPU.ActiveCfg = Release|Any CPU
19 | {B3B0D47D-0B5D-4BAC-B9DB-1D416960423F}.Release|Any CPU.Build.0 = Release|Any CPU
20 | {22615F90-D3FE-4FEB-B8F7-3009FF5825E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {22615F90-D3FE-4FEB-B8F7-3009FF5825E4}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {22615F90-D3FE-4FEB-B8F7-3009FF5825E4}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {22615F90-D3FE-4FEB-B8F7-3009FF5825E4}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {DF394E4E-231F-4208-BB02-E9214B048DA9}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # NetBenchmark
2 | tpc http and websocket performance benchmark components
3 | ## package
4 | https://www.nuget.org/packages/BeetleX.NetBenchmark/
5 | ## tcp
6 | ``` csharp
7 | class Program
8 | {
9 | static void Main(string[] args)
10 | {
11 | var data = StringPacket.RamdomString(512);
12 | var runer = Benchmark.Tcp("192.168.2.19", 9090, 200,
13 | async (tcp, token) =>
14 | {
15 | tcp.Send(data);
16 | await tcp.Receive();
17 | }
18 | );
19 | runer.Run();
20 | runer.Print();
21 | }
22 | }
23 | ```
24 | ## tcp results
25 | 
26 | ## http
27 | ``` csharp
28 | class Program
29 | {
30 | static void Main(string[] args)
31 | {
32 | var runer = Benchmark.Http(new Uri("http://192.168.2.19:5000"), 100,
33 | async (http, token) =>
34 | {
35 | await http.Get("/api/values");
36 | await http.PostJson("/api/values", "beetlex.io");
37 | });
38 | runer.Run();
39 | runer.Print();
40 | }
41 | }
42 | ```
43 | ## http result
44 | 
45 | ## websocket
46 | ``` csharp
47 | class Program
48 | {
49 | static void Main(string[] args)
50 | {
51 | var runer = Benchmark.WebsocketJson(new Uri("ws://192.168.2.19:8080"), 100,
52 | async (ws, token) =>
53 | {
54 | ws.TimeOut = 1000 * 5;
55 | ws.Send(new { url = "/json" });
56 | var result = await ws.Receive();
57 | });
58 | runer.Run();
59 | runer.Print();
60 | }
61 | }
62 | ```
63 | ## result
64 | 
65 |
--------------------------------------------------------------------------------
/NetBenchmark/NetBenchmark.ConsoleTest/Program.cs:
--------------------------------------------------------------------------------
1 | using BeetleX.Buffers;
2 | using BeetleX.Clients;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Threading.Tasks;
6 |
7 | namespace NetBenchmark.ConsoleTest
8 | {
9 | //websocket
10 | //var runer = Benchmark.WebsocketText(new Uri("ws://192.168.2.19:8080"), 100,
11 | // async (ws, token) =>
12 | // {
13 | // ws.TimeOut = 1000 * 5;
14 | // ws.Send("{\"url\":\"/json\"}");
15 | // var result = await ws.Receive();
16 | // });
17 | //tcp
18 | //var runer = Benchmark.Tcp("192.168.2.19", 9090, 200,
19 | // async (tcp, token) =>
20 | // {
21 | // tcp.Send("Test");
22 | // await tcp.Receive();
23 | // }
24 | //);
25 | //http
26 | //var runer = Benchmark.Http(new Uri("http://192.168.2.19:5000"), 100,
27 | // async (http, token) =>
28 | // {
29 | // await http.Get("/api/values");
30 | // });
31 | class Program
32 | {
33 | static void Main(string[] args)
34 | {
35 | var runer = Benchmark.Http(new Uri("http://192.168.2.19"), 100,
36 | async (http, token) =>
37 | {
38 | await http.Get("/customers?count=40");
39 | });
40 | runer.Run();
41 | runer.Print();
42 | }
43 | }
44 |
45 | public class StringPacket : BeetleX.Packets.FixeHeaderClientPacket
46 | {
47 | public static byte[] RamdomString(int length = 1024)
48 | {
49 | var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
50 | var stringChars = new char[length];
51 | var random = new Random();
52 | for (int i = 0; i < length; i++)
53 | {
54 | stringChars[i] = chars[random.Next(length % chars.Length)];
55 | }
56 | return System.Text.Encoding.UTF8.GetBytes(stringChars);
57 |
58 | }
59 |
60 | public override IClientPacket Clone()
61 | {
62 | return new StringPacket();
63 | }
64 |
65 | protected override object OnRead(IClient client, PipeStream stream)
66 | {
67 | stream.ReadFree(CurrentSize);
68 | return null;
69 | }
70 |
71 | protected override void OnWrite(object data, IClient client, PipeStream stream)
72 | {
73 | if (data is byte[] bytes)
74 | stream.Write(bytes, 0, bytes.Length);
75 | else
76 | stream.Write((string)data);
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/NetBenchmark/NetBenchmark/Counter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace NetBenchmark
6 | {
7 | public class Counter
8 | {
9 | public Counter(string name)
10 | {
11 | Name = name;
12 | }
13 |
14 | public string Name { get; set; }
15 |
16 | private long mQuantity { get; set; }
17 |
18 | private long mValue;
19 |
20 | private long mLastValue;
21 |
22 | private double mLastTime;
23 |
24 | private long mRps;
25 |
26 | private long mCount;
27 |
28 | private long mRpsCount;
29 |
30 | public long Value => mValue;
31 |
32 | public long Rps => mRps;
33 |
34 | public long Max { get; private set; }
35 |
36 | public long Avg { get; private set; }
37 |
38 | public long Min { get; private set; }
39 |
40 | public void Add(long value)
41 | {
42 | System.Threading.Interlocked.Add(ref mValue, value);
43 | }
44 |
45 | public void Calculate()
46 | {
47 | if (mValue > mLastValue)
48 | {
49 | double stime = BeetleX.TimeWatch.GetTotalSeconds();
50 | double time = stime - mLastTime;
51 | var svalue = mValue - mLastValue;
52 | mQuantity++;
53 | mRps = (long)(svalue / time);
54 | mLastValue = Value;
55 | mLastTime = stime;
56 |
57 | if (Rps > Max)
58 | Max = Rps;
59 | if (mQuantity > 3)
60 | {
61 | if (Rps < Min || Min == 0)
62 | Min = Rps;
63 | }
64 |
65 | mCount++;
66 | mRpsCount += mRps;
67 | Avg = mRpsCount / mCount;
68 | }
69 |
70 | }
71 |
72 | public void Reset()
73 | {
74 | mLastTime = BeetleX.TimeWatch.GetTotalSeconds();
75 | }
76 |
77 | public void Print(StringBuilder sb, int baseValue = 1, string unit = "")
78 | {
79 | sb.Append("|");
80 | var value = $"{Name}|".PadLeft(18);
81 | sb.Append(value);
82 |
83 | value = $"{Max / baseValue:###,###,##0}|".PadLeft(10);
84 | sb.Append(value);
85 |
86 | value = $"{Avg / baseValue:###,###,##0}|".PadLeft(10);
87 | sb.Append(value);
88 |
89 | value = $"{Min / baseValue:###,###,##0}|".PadLeft(10);
90 | sb.Append(value);
91 |
92 | value = $"{mRps / baseValue:###,###,##0}/{mValue / baseValue:###,###,##0}{unit}|".PadLeft(26);
93 | sb.Append(value);
94 | sb.AppendLine("");
95 |
96 | }
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/NetBenchmark/NetBenchmark/WebSocketTester.cs:
--------------------------------------------------------------------------------
1 | using BeetleX.Http.WebSockets;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace NetBenchmark
8 | {
9 | public class WebSocketFrameTester : ITester
10 | where Token : new()
11 | {
12 | public WebSocketFrameTester(Uri uri)
13 | {
14 | Client = new WSClient(uri.ToString());
15 | }
16 |
17 | public Token Tag { get; set; } = new Token();
18 |
19 | public Runner Runner { get; set; }
20 |
21 | public WSClient Client { get; set; }
22 |
23 | public Func Handler { get; set; }
24 |
25 |
26 | public async Task Execute()
27 | {
28 | await Client.Connect();
29 | Client.Client.SocketProcessHandler = Runner;
30 | await Handler(Client, Tag);
31 | }
32 | }
33 |
34 | public class TestWSClient : WSClient
35 | {
36 | public TestWSClient(Uri uri) : base(uri.ToString()) { }
37 |
38 | public override byte[] GetReadFrameDataBuffer(int length)
39 | {
40 | return base.GetReadFrameDataBuffer(length);
41 | }
42 | public override void FreeReadFrameDataBuffer(byte[] data)
43 | {
44 | base.FreeReadFrameDataBuffer(data);
45 | }
46 | }
47 |
48 |
49 |
50 | public class WebSocketTextTester : ITester
51 | where Token : new()
52 | {
53 |
54 | public WebSocketTextTester(Uri uri)
55 | {
56 | Client = new TextClient(uri.ToString());
57 | }
58 |
59 | public Token Tag { get; set; } = new Token();
60 |
61 | public Runner Runner { get; set; }
62 |
63 | public TextClient Client { get; set; }
64 |
65 | public Func Handler { get; set; }
66 |
67 |
68 | public async Task Execute()
69 | {
70 | await Client.Connect();
71 | Client.Client.SocketProcessHandler = Runner;
72 | await Handler(Client, Tag);
73 | }
74 | }
75 |
76 |
77 |
78 | public class WebSocketJsonTester : ITester
79 | where Token : new()
80 | {
81 | public WebSocketJsonTester(Uri uri)
82 | {
83 | Client = new JsonClient(uri.ToString());
84 | }
85 |
86 | public Token Tag { get; set; } = new Token();
87 |
88 | public Runner Runner { get; set; }
89 |
90 | public JsonClient Client { get; set; }
91 |
92 | public Func Handler { get; set; }
93 |
94 |
95 | public async Task Execute()
96 | {
97 | await Client.Connect();
98 | Client.Client.SocketProcessHandler = Runner;
99 | await Handler(Client, Tag);
100 | }
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/NetBenchmark/NetBenchmark/Benchmark.cs:
--------------------------------------------------------------------------------
1 | using BeetleX.Http.WebSockets;
2 | using System;
3 | using System.Threading.Tasks;
4 |
5 | namespace NetBenchmark
6 | {
7 | public class Benchmark
8 | {
9 | public static Runner Tcp(string host, int port, int connections,
10 | Func handler)
11 | where Packet : BeetleX.Clients.IClientPacket, new()
12 | where Token : new()
13 | {
14 | Runner runer = new Runner();
15 | runer.Name = $"TCP benchmark [{host}@{port}] [connections:{connections:###,###,###}]";
16 | for (int i = 0; i < connections; i++)
17 | {
18 | TCPTester tester = new TCPTester();
19 | tester.Runner = runer;
20 | tester.Handler = handler;
21 | tester.Client = new BeetleX.Clients.AwaiterClient(host, port, new Packet());
22 | tester.Client.Client.SocketProcessHandler = runer;
23 | runer.Testers.Add(tester);
24 | }
25 | return runer;
26 |
27 | }
28 |
29 | public static Runner Http(Uri host, int connections, Func handler)
30 | where Token : new()
31 | {
32 | BeetleX.Http.Clients.HttpClientPoolFactory.SetPoolInfo(host.ToString(), connections + 10, 5000);
33 | Runner runer = new Runner();
34 | runer.Name = $"HTTP [{host}][Connections:{connections:###,###,###}]";
35 | for (int i = 0; i < connections; i++)
36 | {
37 | HttpTester tester = new HttpTester(host);
38 | tester.Handler = handler;
39 | tester.Runner = runer;
40 | runer.Testers.Add(tester);
41 | }
42 | return runer;
43 | }
44 |
45 |
46 | public static Runner Websocket(Uri host, int connections, Func handler)
47 | where Token : new()
48 | {
49 | Runner runer = new Runner();
50 | runer.Name = $"Websockt [{host}] [connections:{connections:###,###,###}]";
51 | for (int i = 0; i < connections; i++)
52 | {
53 | WebSocketFrameTester tester = new WebSocketFrameTester(host);
54 | tester.Handler = handler;
55 | tester.Runner = runer;
56 | runer.Testers.Add(tester);
57 | }
58 | return runer;
59 | }
60 |
61 | public static Runner WebsocketText(Uri host, int connections, Func handler)
62 | where Token : new()
63 | {
64 | Runner runer = new Runner();
65 | runer.Name = $"Websockt text [{host}] [connections:{connections:###,###,###}]";
66 | for (int i = 0; i < connections; i++)
67 | {
68 | WebSocketTextTester tester = new WebSocketTextTester(host);
69 | tester.Handler = handler;
70 | tester.Runner = runer;
71 | runer.Testers.Add(tester);
72 | }
73 | return runer;
74 | }
75 |
76 | public static Runner WebsocketJson(Uri host, int connections, Func handler)
77 | where Token : new()
78 | {
79 | Runner runer = new Runner();
80 | runer.Name = $"Websockt json [{host}] [connections:{connections:###,###,###}]";
81 | for (int i = 0; i < connections; i++)
82 | {
83 | WebSocketJsonTester tester = new WebSocketJsonTester(host);
84 | tester.Handler = handler;
85 | tester.Runner = runer;
86 | runer.Testers.Add(tester);
87 | }
88 | return runer;
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/NetBenchmark/NetBenchmark/HttpTester.cs:
--------------------------------------------------------------------------------
1 | using BeetleX.Buffers;
2 | using BeetleX.Http.Clients;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace NetBenchmark
9 | {
10 | public class HttpTester : ITester, IHttpHandler
11 | where Token : new()
12 | {
13 |
14 | public HttpTester(Uri uri)
15 | {
16 | mHttpHost = HttpHost.GetHttpHost(uri);
17 | }
18 |
19 | private BeetleX.Http.Clients.HttpHost mHttpHost;
20 |
21 | public Func Handler { get; set; }
22 |
23 | public Runner Runner { get; set; }
24 |
25 | public Token Tag { get; set; } = new Token();
26 |
27 | public async Task Execute()
28 | {
29 | await Handler(this, Tag);
30 | }
31 |
32 | private void GetConnection(BeetleX.Clients.AsyncTcpClient client)
33 | {
34 | client.SocketProcessHandler = Runner;
35 | }
36 |
37 | public Task Get(string url, Dictionary queryString = null)
38 | {
39 | return Get(url, queryString, null);
40 | }
41 |
42 | public async Task Get(string url, Dictionary queryString, Dictionary header = null)
43 | {
44 | var request = mHttpHost.Get(url, header, queryString, new CustomuFormUrlFormater());
45 | request.GetConnection = GetConnection;
46 | var response = await request.Execute();
47 | if (response.Exception != null)
48 | throw response.Exception;
49 | }
50 |
51 | public async Task Post(string url, Dictionary queryString, Dictionary header, Dictionary data)
52 | {
53 | var request = mHttpHost.Post(url, header, queryString, data, new CustomuFormUrlFormater());
54 | request.GetConnection = GetConnection;
55 | var response = await request.Execute();
56 | if (response.Exception != null)
57 | throw response.Exception;
58 | }
59 |
60 | public async Task PostJson(string url, Dictionary queryString, Dictionary header, object data)
61 | {
62 | var request = mHttpHost.Post(url, header, queryString, data, new CustonJsonFormater());
63 | request.GetConnection = GetConnection;
64 | var response = await request.Execute();
65 | if (response.Exception != null)
66 | throw response.Exception;
67 | }
68 |
69 | public Task Post(string url, Dictionary data)
70 | {
71 | return Post(url, null, null, data);
72 | }
73 |
74 | public Task PostJson(string url, object data)
75 | {
76 | return PostJson(url, null, null, data);
77 | }
78 | }
79 |
80 | public class CustomuFormUrlFormater : FormUrlFormater
81 | {
82 | public override object Deserialization(Response response, PipeStream stream, Type type, int length)
83 | {
84 | stream.ReadFree(length);
85 | return null;
86 | }
87 | }
88 | public class CustonJsonFormater : JsonFormater
89 | {
90 | public override object Deserialization(Response response, PipeStream stream, Type type, int length)
91 | {
92 | stream.ReadFree(length);
93 | return null;
94 | }
95 |
96 | }
97 |
98 |
99 | public interface IHttpHandler
100 | {
101 |
102 | Task Get(string url, Dictionary queryString = null);
103 |
104 | Task Get(string url, Dictionary queryString, Dictionary header = null);
105 |
106 | Task Post(string url, Dictionary queryString, Dictionary heaer, Dictionary data);
107 |
108 | Task Post(string url, Dictionary data);
109 |
110 | Task PostJson(string url, Dictionary queryString, Dictionary heaer, object data);
111 |
112 | Task PostJson(string url, object data);
113 | }
114 |
115 | }
116 |
--------------------------------------------------------------------------------
/NetBenchmark/NetBenchmark/TimeStatistics.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using System.Linq;
5 | namespace NetBenchmark
6 | {
7 | public class TimesStatistics
8 | {
9 |
10 | private long mCount;
11 |
12 | public long Count => mCount;
13 |
14 | public List Items { get; private set; } = new List();
15 |
16 | public TimesStatistics()
17 | {
18 | TimeConuterItem item = new TimeConuterItem("1", "<1ms");
19 | Items.Add(item);
20 |
21 | item = new TimeConuterItem("1_5", "1-5ms");
22 | Items.Add(item);
23 |
24 | item = new TimeConuterItem("1_10", "1-10ms");
25 | Items.Add(item);
26 |
27 | item = new TimeConuterItem("10_50", "10ms-50ms");
28 | Items.Add(item);
29 |
30 | item = new TimeConuterItem("50_100", "50ms-100ms");
31 | Items.Add(item);
32 |
33 | item = new TimeConuterItem("100_200", "100ms-200ms");
34 | Items.Add(item);
35 |
36 | item = new TimeConuterItem("200_500", "200ms-500ms");
37 | Items.Add(item);
38 |
39 | item = new TimeConuterItem("500_1000", "500ms-1s");
40 | Items.Add(item);
41 |
42 | item = new TimeConuterItem("1000_5000", "1s-5s");
43 | Items.Add(item);
44 |
45 | item = new TimeConuterItem("5000", ">5s");
46 | Items.Add(item);
47 | }
48 |
49 | public void Print(StringBuilder sb)
50 | {
51 | foreach (var item in Items)
52 | {
53 | if (item.Count == 0)
54 | continue;
55 | var p = (int)(((double)item.Count / (double)Count) * 10000);
56 | if (p < 0)
57 | p = 0;
58 | var pe = (double)p / 100;
59 | int pcount = (int)(pe / 5);
60 | sb.Append('|');
61 | string value = $"{item.DisplayName} ".PadLeft(19);
62 | sb.Append(value);
63 | sb.Append($"{item.Count:###,###,##0} ".PadLeft(20));
64 | sb.Append("[");
65 | value = "".PadLeft(pcount, '=');
66 | value = value.PadRight(20, ' ');
67 | sb.Append(value);
68 | sb.Append("]");
69 | sb.Append($"{pe}%|".PadLeft(13));
70 |
71 | sb.AppendLine("");
72 |
73 | }
74 | }
75 |
76 | public void Add(long time)
77 | {
78 | System.Threading.Interlocked.Increment(ref mCount);
79 |
80 | if (time < 1)
81 | {
82 | Items[0].Add();
83 | }
84 | else if (time < 5)
85 | {
86 | Items[1].Add();
87 | }
88 | else if (time < 10)
89 | {
90 | Items[2].Add();
91 | }
92 | else if (time >= 10 && time < 50)
93 | {
94 | Items[3].Add();
95 | }
96 | else if (time >= 50 && time < 100)
97 | {
98 | Items[4].Add();
99 | }
100 | else if (time >= 100 && time < 200)
101 | {
102 | Items[5].Add();
103 | }
104 | else if (time >= 200 && time < 500)
105 | {
106 | Items[6].Add();
107 | }
108 | else if (time >= 500 && time < 1000)
109 | {
110 | Items[7].Add();
111 | }
112 | else if (time >= 1000 && time < 5000)
113 | {
114 | Items[8].Add();
115 | }
116 | else if (time >= 5000)
117 | {
118 | Items[9].Add();
119 | }
120 | }
121 | public class TimeConuterItem
122 | {
123 | public TimeConuterItem(string name, string displayName = null)
124 | {
125 | Name = name;
126 | if (displayName == null)
127 | displayName = name;
128 | DisplayName = displayName;
129 | }
130 |
131 | public string DisplayName { get; set; }
132 |
133 | public string Name { get; set; }
134 |
135 | private int mCount;
136 |
137 | public int Count => mCount;
138 |
139 | public void Add()
140 | {
141 | System.Threading.Interlocked.Increment(ref mCount);
142 | }
143 | }
144 | }
145 |
146 |
147 | }
148 |
--------------------------------------------------------------------------------
/NetBenchmark/NetBenchmark/Runner.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Net.Sockets;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using BeetleX;
7 | using BeetleX.Clients;
8 |
9 | namespace NetBenchmark
10 | {
11 | public class Runner : BeetleX.Clients.IClientSocketProcessHandler
12 | {
13 |
14 | public const int WIDTH = 75;
15 |
16 | public string Name { get; set; }
17 |
18 | public Counter Success { get; private set; } = new Counter("Success");
19 |
20 | public Counter Error { get; private set; } = new Counter("Error");
21 |
22 | public Counter ReceiveBytes { get; private set; } = new Counter("Read");
23 |
24 | public Counter SendBytes { get; private set; } = new Counter("Write");
25 |
26 | public bool Status { get; set; } = false;
27 |
28 | public List Testers { get; private set; } = new List();
29 |
30 | private TimesStatistics mTimesStatistics = new TimesStatistics();
31 |
32 | public Action OnError { get; set; }
33 |
34 | private System.Diagnostics.Stopwatch Stopwatch = new System.Diagnostics.Stopwatch();
35 |
36 | private async Task OnPreheating(ITester item)
37 | {
38 | for (int i = 0; i < 2; i++)
39 | {
40 | try
41 | {
42 | await item.Execute();
43 | }
44 | catch (Exception e_)
45 | {
46 | try
47 | {
48 | OnError?.Invoke(item, e_);
49 | }
50 | catch { }
51 | }
52 |
53 | }
54 | }
55 |
56 | private async void OnRunItem(ITester item)
57 | {
58 | while (Status)
59 | {
60 | var time = BeetleX.TimeWatch.GetElapsedMilliseconds();
61 | try
62 | {
63 |
64 | await item.Execute();
65 | Success.Add(1);
66 | }
67 | catch (Exception e_)
68 | {
69 | Error.Add(1);
70 | try
71 | {
72 | OnError?.Invoke(item, e_);
73 | }
74 | catch { }
75 | }
76 | finally
77 | {
78 | mTimesStatistics.Add(BeetleX.TimeWatch.GetElapsedMilliseconds() - time);
79 | }
80 | }
81 | }
82 |
83 | private void OnStatistics(object state)
84 | {
85 | if (Status)
86 | {
87 | Success.Calculate();
88 | Error.Calculate();
89 | ReceiveBytes.Calculate();
90 | SendBytes.Calculate();
91 | }
92 | }
93 |
94 | private System.Threading.Timer mStatisticsTimer;
95 |
96 | public void Print()
97 | {
98 | StringBuilder sb = new StringBuilder();
99 | while (true)
100 | {
101 | sb.Clear();
102 | string value = "TCP/HTTP/WEBSOCKET Benchmark";
103 | Console.CursorTop = 0;
104 | Console.CursorLeft = 0;
105 |
106 | sb.AppendLine("");
107 | int span = WIDTH / 2 - value.Length / 2;
108 | sb.AppendLine("".PadLeft(span) + value);
109 |
110 |
111 | sb.AppendLine("");
112 |
113 | value = Name;
114 | span = 70 / 2 - value.Length / 2;
115 | sb.AppendLine("".PadLeft(span) + value);
116 |
117 |
118 | sb.AppendLine("-".PadRight(WIDTH, '-'));
119 | sb.Append("|");
120 | value = $"Name|".PadLeft(18);
121 | sb.Append(value);
122 |
123 | value = $"Max|".PadLeft(10);
124 | sb.Append(value);
125 |
126 | value = $"Avg|".PadLeft(10);
127 | sb.Append(value);
128 |
129 | value = $"Min|".PadLeft(10);
130 | sb.Append(value);
131 |
132 | value = $"RPS/Total|".PadLeft(26);
133 | sb.Append(value);
134 | sb.AppendLine("");
135 |
136 | sb.AppendLine("-".PadRight(WIDTH, '-'));
137 | Success.Print(sb);
138 | Error.Print(sb);
139 | value = "Network bandwidth";
140 | span = WIDTH / 2 - value.Length / 2;
141 | sb.Append("".PadLeft(span, '-') + value)
142 | .AppendLine("".PadRight(span, '-'));
143 |
144 | ReceiveBytes.Print(sb, 1024, "(KB)");
145 | SendBytes.Print(sb, 1024, "(KB)");
146 |
147 |
148 | value = "Response latency";
149 | span = WIDTH / 2 - value.Length / 2;
150 | sb.Append("".PadLeft(span, '-') + value)
151 | .AppendLine("".PadRight(span + 1, '-'));
152 |
153 | mTimesStatistics.Print(sb);
154 | sb.AppendLine("-".PadRight(WIDTH, '-'));
155 |
156 | value = $"Run time:{Stopwatch.Elapsed}";
157 | span = WIDTH / 2 - value.Length / 2;
158 | sb.Append("|");
159 | sb.AppendLine("".PadLeft(span) + value + "".PadRight(span-2) + "|");
160 | ;
161 | sb.AppendLine("-".PadRight(WIDTH, '-'));
162 |
163 | value = "Copyright © beetlex.io 2019-2021 email:henryfan@msn.com";
164 | span = WIDTH / 2 - value.Length / 2;
165 | sb.AppendLine("".PadLeft(span) + value);
166 |
167 | Console.WriteLine(sb);
168 | System.Threading.Thread.Sleep(1000);
169 | }
170 |
171 | }
172 |
173 | public async void Run()
174 | {
175 | Status = true;
176 | foreach (var item in Testers)
177 | {
178 | await OnPreheating(item);
179 | }
180 | Stopwatch.Restart();
181 | Success.Reset();
182 | Error.Reset();
183 | ReceiveBytes.Reset();
184 | SendBytes.Reset();
185 | foreach (var item in Testers)
186 | {
187 | Task.Run(() => OnRunItem(item));
188 | }
189 | mStatisticsTimer = new System.Threading.Timer(OnStatistics, null, 1000, 1000);
190 | }
191 |
192 | public void Stop()
193 | {
194 | Status = false;
195 | if (mStatisticsTimer != null)
196 | mStatisticsTimer.Dispose();
197 | }
198 |
199 | public void ReceiveCompleted(IClient client, SocketAsyncEventArgs e)
200 | {
201 | ReceiveBytes.Add(e.BytesTransferred);
202 | }
203 |
204 | public void SendCompleted(IClient client, SocketAsyncEventArgs e, bool end)
205 | {
206 | SendBytes.Add(e.BytesTransferred);
207 | }
208 | }
209 | }
210 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------