From ff59d3f5ad431287dc6f689047ed0b8a7f96056a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 30 Dec 2021 19:20:33 +0100 Subject: [PATCH] Reduce allocations for ComputeContext async execution --- .../Dispatching/DispatchingBenchmark.cs | 28 +++++ .../ComputeSharp.NetStandard.projitems | 1 - .../Threading.Tasks/TaskCompletionSource.cs | 15 --- .../Graphics/GraphicsDevice.Execute.cs | 119 +++++++++++++++--- 4 files changed, 132 insertions(+), 31 deletions(-) delete mode 100644 src/ComputeSharp.NetStandard/System/Threading.Tasks/TaskCompletionSource.cs diff --git a/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs b/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs index 395624e0..e94a1e95 100644 --- a/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs +++ b/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Configs; @@ -8,6 +9,7 @@ namespace ComputeSharp.Benchmark.Blas; /// A that benchmarks the shader dispatch times. /// [GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)] +[MemoryDiagnoser] public partial class DispatchingBenchmark : IDisposable { /// @@ -53,6 +55,18 @@ public partial class DispatchingBenchmark : IDisposable context.For(64, new TestShader(Buffer!)); } + /// + /// Invokes a single shader through a compute context, asynchronously. + /// + [Benchmark] + [BenchmarkCategory("SINGLE")] + public async Task Compute_Single_WithContext_Async() + { + await using var context = GraphicsDevice.Default.CreateComputeContext(); + + context.For(64, new TestShader(Buffer!)); + } + /// /// Invokes two empty compute shaders one by one. /// @@ -78,6 +92,20 @@ public partial class DispatchingBenchmark : IDisposable context.For(64, new TestShader(Buffer!)); } + /// + /// Invokes two empty compute shaders in a batch, asynchronously. + /// + [Benchmark] + [BenchmarkCategory("MULTIPLE")] + public async Task Compute_Multiple_WithContext_Async() + { + await using var context = GraphicsDevice.Default.CreateComputeContext(); + + context.For(64, new TestShader(Buffer!)); + context.Barrier(Buffer!); + context.For(64, new TestShader(Buffer!)); + } + [AutoConstructor] internal readonly partial struct TestShader : IComputeShader { diff --git a/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems b/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems index 0e93ea84..3d8e7be8 100644 --- a/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems +++ b/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems @@ -27,6 +27,5 @@ - \ No newline at end of file diff --git a/src/ComputeSharp.NetStandard/System/Threading.Tasks/TaskCompletionSource.cs b/src/ComputeSharp.NetStandard/System/Threading.Tasks/TaskCompletionSource.cs deleted file mode 100644 index b90c0ddd..00000000 --- a/src/ComputeSharp.NetStandard/System/Threading.Tasks/TaskCompletionSource.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace System.Threading.Tasks; - -/// -/// A polyfill type that mirrors the non-generic type on .NET 6. -/// -internal sealed class TaskCompletionSource : TaskCompletionSource -{ - /// - /// Transitions the underlying into the state. - /// - public void SetResult() - { - SetResult(null); - } -} diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs index 1a1866d4..4c40fe99 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs @@ -1,7 +1,11 @@ -using System.Runtime.CompilerServices; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; +using System.Threading.Tasks.Sources; using ComputeSharp.Core.Extensions; using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Commands.Interop; @@ -120,13 +124,11 @@ unsafe partial class GraphicsDevice : NativeObject } // Setup the awaitable task - Task computeTask = WaitForFenceAsync( + return WaitForFenceAsync( updatedFenceValue, this, commandList.DetachD3D12CommandList(), - commandList.DetachD3D12CommandAllocator()); - - return new(computeTask); + commandList.DetachD3D12CommandAllocator()).AsValueTask(); } /// @@ -135,9 +137,9 @@ unsafe partial class GraphicsDevice : NativeObject private struct CallbackContext { /// - /// The wrapping the object to signal completion. + /// The wrapping the object to signal completion. /// - public GCHandle TaskCompletionSourceHandle; + public GCHandle WaitForFenceValueTaskSourceHandle; /// /// The wrapping the instance in use. @@ -167,9 +169,9 @@ unsafe partial class GraphicsDevice : NativeObject /// The instance executing the operations. /// The used to queue the operations. /// The object backing . - /// The object representing the operation to wait for. + /// The object representing the operation to wait for. /// This method is only supported for compute operations. - private static Task WaitForFenceAsync( + private static WaitForFenceValueTaskSource WaitForFenceAsync( ulong d3D12FenceValue, GraphicsDevice device, ID3D12GraphicsCommandList* d3D12GraphicsCommandList, @@ -179,10 +181,10 @@ unsafe partial class GraphicsDevice : NativeObject device.d3D12ComputeFence.Get()->SetEventOnCompletion(d3D12FenceValue, eventHandle).Assert(); - TaskCompletionSource taskCompletionSource = new(); + WaitForFenceValueTaskSource waitForFenceValueTaskSource = WaitForFenceValueTaskSource.Rent(); CallbackContext* callbackContext = (CallbackContext*)NativeMemory.Alloc((nuint)sizeof(CallbackContext)); - callbackContext->TaskCompletionSourceHandle = GCHandle.Alloc(taskCompletionSource); + callbackContext->WaitForFenceValueTaskSourceHandle = GCHandle.Alloc(waitForFenceValueTaskSource); callbackContext->GraphicsDeviceHandle = GCHandle.Alloc(device); callbackContext->D3D12GraphicsCommandList = d3D12GraphicsCommandList; callbackContext->D3D12CommandAllocator = d3D12CommandAllocator; @@ -202,7 +204,7 @@ unsafe partial class GraphicsDevice : NativeObject dwMilliseconds: Windows.INFINITE, dwFlags: 0); - return taskCompletionSource.Task; + return waitForFenceValueTaskSource; } /// @@ -215,13 +217,13 @@ unsafe partial class GraphicsDevice : NativeObject { CallbackContext* callbackContext = (CallbackContext*)pContext; - TaskCompletionSource taskCompletionSource = Unsafe.As(callbackContext->TaskCompletionSourceHandle.Target)!; + WaitForFenceValueTaskSource waitForFenceValueTaskSource = Unsafe.As(callbackContext->WaitForFenceValueTaskSourceHandle.Target)!; GraphicsDevice device = Unsafe.As(callbackContext->GraphicsDeviceHandle.Target)!; ID3D12GraphicsCommandList* d3D12GraphicsCommandList = callbackContext->D3D12GraphicsCommandList; ID3D12CommandAllocator* d3D12CommandAllocator = callbackContext->D3D12CommandAllocator; HANDLE eventHandle = callbackContext->EventHandle; - callbackContext->TaskCompletionSourceHandle.Free(); + callbackContext->WaitForFenceValueTaskSourceHandle.Free(); callbackContext->GraphicsDeviceHandle.Free(); device.computeCommandListPool.Return(d3D12GraphicsCommandList, d3D12CommandAllocator); @@ -230,6 +232,93 @@ unsafe partial class GraphicsDevice : NativeObject NativeMemory.Free(callbackContext); - taskCompletionSource.SetResult(); + waitForFenceValueTaskSource.Complete(); + } + + /// + /// A reusable type. + /// + private sealed class WaitForFenceValueTaskSource : IValueTaskSource + { + /// + /// The shared holding the reusable instances. + /// + private static readonly ConcurrentQueue ValueTaskSourceQueue = new(); + + /// + /// The approximate count of currently enqueued instances in . + /// + private static volatile int queuedValueTaskSourceCount; + + /// + /// The wrapped instance being used. + /// + private ManualResetValueTaskSourceCore manualResetValueTaskSource; + + /// + /// Rents a instance. + /// + /// A instance to use. + public static WaitForFenceValueTaskSource Rent() + { + if (ValueTaskSourceQueue.TryDequeue(out WaitForFenceValueTaskSource? valueTaskSource)) + { + _ = Interlocked.Decrement(ref queuedValueTaskSourceCount); + } + else + { + valueTaskSource = new WaitForFenceValueTaskSource(); + } + + return valueTaskSource; + } + + /// + /// Creates a new from the current instance. + /// + /// A used to wait for the underlying operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ValueTask AsValueTask() + { + return new(this, this.manualResetValueTaskSource.Version); + } + + /// + /// Signals the current instance for completion. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Complete() + { + this.manualResetValueTaskSource.SetResult(null); + } + + /// + public void GetResult(short token) + { + _ = this.manualResetValueTaskSource.GetResult(token); + + this.manualResetValueTaskSource.Reset(); + + if (Interlocked.Increment(ref queuedValueTaskSourceCount) < 16) + { + ValueTaskSourceQueue.Enqueue(this); + } + else + { + _ = Interlocked.Decrement(ref queuedValueTaskSourceCount); + } + } + + /// + public ValueTaskSourceStatus GetStatus(short token) + { + return this.manualResetValueTaskSource.GetStatus(token); + } + + /// + public void OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) + { + this.manualResetValueTaskSource.OnCompleted(continuation, state, token, flags); + } } }