Repository navigation
Open
Labels
api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Net.Socketstenet-performancePerformance related issue
Milestone
Description
As part of looking at multiplexing and perf for Linux, I did a quick benchmark of "gather socket I/O", i.e. writing multiple buffers to a socket in one go. This would open up some interesting possibilities to further push perf (and also considerably simplify things for the design). Here are some quick results and observations:
- Socket.SendPacketsAsync seems to be particularly bad on Linux, since... it doesn't actually write the buffers in one go, but rather writes them one-by-one.
- Socket.SendPacketsAsync also requires providing a list of SendPacketsElement, which is an immutable reference type. That means that unless the buffers and offsets/counts are completely fixed, heap allocations are necessary for each write.
- Socket.SendAsync with SocketAsyncEventArgs.BufferList is much better ("only" 3 times slower than regular single-buffer). However, each time SocketAsyncEventArgs.BufferList is set, the whole array is copied internally to avoid issues with subsequent changes. This again means that it's impossible to change the buffers/counts/offsets without triggering an expensive re-copying. Note that this re-copying is not done in the benchmark below, which reuses the same buffer list.
- The parameters (NumBuffers/BufferSize) are currently set to a typical Npgsql muiltiplexing scenario for TE Fortunes, but can obviously be played with.
In other words, there's definitely work needed (and possibly new APIs) if these are to be useful in a high-perf scenario. Hopefully I didn't do miss anything or do any silliness in the benchmark, let me know.
Results:
BenchmarkDotNet=v0.12.0, OS=ubuntu 20.04
Intel Xeon W-2133 CPU 3.60GHz, 1 CPU, 12 logical and 6 physical cores
.NET Core SDK=5.0.100-preview.3.20216.6
[Host] : .NET Core 3.1.1 (CoreCLR 4.700.19.60701, CoreFX 4.700.19.60801), X64 RyuJIT
DefaultJob : .NET Core 3.1.1 (CoreCLR 4.700.19.60701, CoreFX 4.700.19.60801), X64 RyuJIT
| Method | NumBuffers | BufferSize | Mean | Error | StdDev |
|---|---|---|---|---|---|
| NetworkStreamSingleBuffer | 25 | 36 | 1.198 us | 0.0114 us | 0.0106 us |
| SocketAsyncEventArgsSingleBuffer | 25 | 36 | 1.145 us | 0.0110 us | 0.0092 us |
| SocketAsyncEventArgsBufferList | 25 | 36 | 3.616 us | 0.0158 us | 0.0132 us |
| SocketAsyncEventArgsSendPackets | 25 | 36 | 42.723 us | 0.2419 us | 0.2145 us |
Benchmark code
public class Program
{
const int Port = 9595;
const string Address = "127.0.0.1";
DummyServer _server;
Socket _socket;
SocketAsyncEventArgs _args;
NetworkStream _networkStream;
ManualResetEventSlim _mre;
[Params(25)]
public int NumBuffers { get; set; }
[Params(36)]
public int BufferSize { get; set; }
Memory<byte> _singleBuffer;
public void SetupServerAndConnect()
{
_server = new DummyServer();
_server.Start();
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Connect(new IPEndPoint(IPAddress.Parse(Address), Port));
}
[GlobalCleanup]
public async Task Cleanup()
{
_args?.Dispose();
_args = null;
_socket.Close();
_socket = null;
_networkStream = null;
await _server.FinishTask;
}
[GlobalSetup(Target = nameof(NetworkStreamSingleBuffer))]
public void SetupNetworkStreamSingleBuffer()
{
SetupServerAndConnect();
_networkStream = new NetworkStream(_socket, ownsSocket: false);
_singleBuffer = new byte[NumBuffers * BufferSize];
}
[GlobalSetup(Target = nameof(SocketAsyncEventArgsSingleBuffer))]
public void SetupSocketAsyncEventArgsSingleBuffer()
{
SetupServerAndConnect();
_args = new SocketAsyncEventArgs();
_args.SetBuffer(new byte[NumBuffers * BufferSize]);
_mre = new ManualResetEventSlim();
_args.Completed += (s, e) => _mre.Set();
}
[GlobalSetup(Target = nameof(SocketAsyncEventArgsBufferList))]
public void SetupSocketAsyncEventArgsBufferList()
{
SetupServerAndConnect();
var bufferList = new List<ArraySegment<byte>>(NumBuffers);
for (var i = 0; i < NumBuffers; i++)
bufferList.Add(new byte[BufferSize]);
_args = new SocketAsyncEventArgs
{
BufferList = bufferList
};
_mre = new ManualResetEventSlim();
_args.Completed += (s, e) => _mre.Set();
}
[GlobalSetup(Target = nameof(SocketAsyncEventArgsSendPackets))]
public void SetupSocketAsyncEventArgsSendPackets()
{
SetupServerAndConnect();
_args = new SocketAsyncEventArgs
{
SendPacketsElements = new SendPacketsElement[NumBuffers]
};
for (var i = 0; i < NumBuffers; i++)
_args.SendPacketsElements[i] = new SendPacketsElement(new byte[BufferSize]);
_mre = new ManualResetEventSlim();
_args.Completed += (s, e) => _mre.Set();
}
[Benchmark]
public void NetworkStreamSingleBuffer()
{
var t = _networkStream.WriteAsync(_singleBuffer);
if (!t.IsCompletedSuccessfully)
throw new Exception("Non-synchronous completion");
}
[Benchmark]
public void SocketAsyncEventArgsSingleBuffer()
{
// Never completes asynchronously, but adding MRE and event handling because SendPacketsAsync needs it
_mre.Reset();
if (_socket.SendAsync(_args))
_mre.Wait();
}
[Benchmark]
public void SocketAsyncEventArgsBufferList()
{
// Never completes asynchronously, but adding MRE and event handling because SendPacketsAsync needs it
_mre.Reset();
if (_socket.SendAsync(_args))
_mre.Wait();
}
[Benchmark]
public void SocketAsyncEventArgsSendPackets()
{
// Note: SendPacketsAsync seems to always returns true (non-synchronous completion)
_mre.Reset();
if (_socket.SendPacketsAsync(_args))
_mre.Wait();
}
static void Main() => BenchmarkRunner.Run<Program>();
class DummyServer
{
TcpListener _listener;
public Task FinishTask { get; private set; }
public void Start()
{
_listener = new TcpListener(IPAddress.Parse(Address), Port);
_listener.Start();
FinishTask = Task.Run(Process);
}
void Process()
{
var client = _listener.AcceptTcpClient();
var buf = new byte[8192];
var stream = client.GetStream();
while (stream.Read(buf, 0, buf.Length) != 0)
{
// Do nothing with the data
}
}
}
}Reacted by Daniel Svensson
Metadata
Metadata
Assignees
Labels
api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Net.Socketstenet-performancePerformance related issue
Activity
stephentoub commentedon May 24, 2020
How many buffers are you using such that this copy shows up in profiles as being "expensive"? This is copying the buffer references/bounds, not the contents of the buffers.
stephentoub commentedon May 24, 2020
From a quick look at the benchmark, you're always copying N bytes, and it's either all in one buffer or split across M buffers? All in one buffer is always going to be faster. The interesting thing to measure/compare is the overhead it takes to get M buffers into one buffer and sending that vs sending the M buffers sequentially vs sending them all at once.
Or am I misunderstanding what's being demonstrated here?
stephentoub commentedon May 24, 2020
This could certainly be improved. The API that exists is closely tied to the Windows API it was originally wrapping, and supports "packets" that are either buffers or files. We need to maintain the relative ordering, and we use sendfile for the files. But the implementation could be changed to build up a list of adjacent buffers and send those in one shot. We'd need to measure to see at what point the overhead of doing so is worthwhile.
roji commentedon May 24, 2020
I probably should have provided a bit more context here. In my current prototype, multiple producers encode directly into different segments of a single large buffer, which is then written and flushed; the disadvantage is that encoding is serialized, since lengths aren't necessarily known in advance, and management of multiple encoding producers would be quite complicated. The ideal situation is for each producer to encode on its own (pooled) buffer, which then gets written/flushed along with the others via a single gather I/O operation. Hence the baseline here was comparing to a single buffer write, without implying that the gather operation should be faster or equal to a one-buffer write.
I've updated the benchmark as suggested, parameterized different buffer numbers and sizes, and executed on both Linux and Windows (different machines though!).
All tests send the same amount of bytes per method call. Full results are below, here are some observations:
Linux results
Windows results
Benchmark code
roji commentedon May 24, 2020
Just to be clear, this isn't urgent and I don't have any immediate pressing need for using this (though I may at some point).
tmds commentedon May 25, 2020
SocketAsyncEventArgsBufferListis allocating:runtime/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs
Lines 237 to 238 in d0e2281
The IOVector and GCHandles could be stackalloced (up to some bound).
stephentoub commentedon May 25, 2020
As the Windows version of this does. Not sure why this one wasn't changed similarly.
tmds commentedon May 25, 2020
@roji Linux defines
UIO_FASTIOVto8. This means up to8iovs (NumBuffers) will be stackalloced in the kernel. It is an interesting nr to try in the benchmarks.@stephentoub I will take a look at doing this for Unix too.
3 remaining items
wfurt commentedon Dec 15, 2022
triage: We should re-run the benchmarks to see where we are. Perhaps close it in favor of the linked issues.
wfurt commentedon Jun 7, 2023
wfurt commentedon Jun 7, 2023
This is latest set with 8.0. But as far as I can tell the
StreamMultipleBuffersdoes more work thenSingleBuffere.g. the tests are not quite in number of written bytes.